Android 暂停启动和停止服务
我正在尝试制作一个简单的小部件,它带有一个按钮,可以通过Android 暂停启动和停止服务,android,android-widget,android-service,android-pendingintent,Android,Android Widget,Android Service,Android Pendingintent,我正在尝试制作一个简单的小部件,它带有一个按钮,可以通过onclickpendingent()启动服务。我可以很好地启动它,但我无法找到阻止它的方法(我知道我可以用BroadcastReceiver或类似的东西来完成,但我希望避免硬代码) 这是我的代码: Intent intent = new Intent(context, myService.class); PendingIntent pendingIntent = PendingIntent.getServi
onclickpendingent()
启动服务。我可以很好地启动它,但我无法找到阻止它的方法(我知道我可以用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!!!!
}
有多种方法可以做到这一点,这里有一种:
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()