PendingIntent用于启动和停止服务

14

我正在尝试制作一个简单的小部件,其中包含一个按钮,可以使用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!!!!
        }
2个回答

29

有多种方法可以做到这一点,下面是其中之一:

    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
我创建了Xamarin Android信号程序,但当信号到来时,我无法显示信号,也就是说,程序不会自动打开。

如果您有新的问题,请通过单击提问按钮来提出。如果它有助于提供上下文,请包含此问题的链接。- 来自审核 - JustSightseeing

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接