PendingIntent启动和停止服务

时间:2013-12-13 17:14:30

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

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

1 个答案:

答案 0 :(得分:22)

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

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

相关问题