我试图与一个按钮一个简单的小工具,开始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!!!! }
Matt.. 25
有多种方法可以做到这一点,这里有一个:
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()
.
有多种方法可以做到这一点,这里有一个:
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()
.