等待启动和停止服务的意图 [英] PendingIntent to launch and stop a Service

查看:61
本文介绍了等待启动和停止服务的意图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个简单的窗口小部件,并带有一个以OnClickPendingIntent()开头的Service的按钮.我可以很好地启动它,但我想不出一种方法来停止它(我知道我可以使用BroadcastReceiver或类似的方法来做到这一点,但我想避免使用硬编码).

I'm trying to make a simple widget with a button that start a Service with the OnClickPendingIntent(). I can start it fine but I can't figure out a way to stop it (I know I can do it with a BroadcastReceiver or something similar but I would like to avoid hardcode).

这是我的代码:

        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!!!!
        }

推荐答案

执行此操作的方法有多种,一种:

There are multiple ways to do this, here's one:

    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().

Then on the service's onStartCommand(), you can check the intent action for "STOP" (you should probably use a better string) and call stopSelf().

这篇关于等待启动和停止服务的意图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆