【问题标题】:PendingIntent to launch and stop a ServicePendingIntent 启动和停止服务
【发布时间】:2014-01-01 13:25:09
【问题描述】:

我正在尝试用一个按钮制作一个简单的小部件,该按钮以OnClickPendingIntent() 开头的Service。我可以很好地启动它,但我无法找到阻止它的方法(我知道我可以使用 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!!!!
        }

【问题讨论】:

    标签: android android-widget android-service android-pendingintent


    【解决方案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()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-22
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2019-04-25
      相关资源
      最近更新 更多