PendingIntent启动和停止服务

 潮爆啊--_317 发布于 2023-02-10 21:58

我试图与一个按钮一个简单的小工具,开始ServiceOnClickPendingIntent().我可以开始很好,但我无法找到一种方法来阻止它(我知道我可以用一个BroadcastReceiver或类似的东西,但我想避免硬编码).

这是我的代码:

        Intent intent = new Intent(context, myService.class);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget);

        if (!ismyserviceup(context)) {
            views.setOnClickPendingIntent(R.id.my_button, pendingIntent);
        } else {
            // i need to stop it!!!!
        }

Matt.. 25

有多种方法可以做到这一点,这里有一个:

    Intent intent = new Intent(context, myService.class);

    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget);

    if (ismyserviceup(context)) {
        intent.setAction("STOP");
    }
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);                
    views.setOnClickPendingIntent(R.id.my_button, pendingIntent);

然后在服务上onStartCommand(),您可以检查"STOP"的意图操作(您应该使用更好的字符串)并调用stopSelf().

1 个回答
  • 有多种方法可以做到这一点,这里有一个:

        Intent intent = new Intent(context, myService.class);
    
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.my_widget);
    
        if (ismyserviceup(context)) {
            intent.setAction("STOP");
        }
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);                
        views.setOnClickPendingIntent(R.id.my_button, pendingIntent);
    

    然后在服务上onStartCommand(),您可以检查"STOP"的意图操作(您应该使用更好的字符串)并调用stopSelf().

    2023-02-10 22:09 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有