我的广播应用程序上有一个持续通知,并且我已经设法从该通知开始主要 Activity ,但现在我正在尝试向通知添加一个按钮以停止流媒体服务。
这是我在服务中的通知方法:
@SuppressWarnings("deprecation")
private void createNotification() {
int myIconId = R.drawable.ic_pause;
Intent mIntent = new Intent(context, StreamingService.class);
Notification notification;
Bundle bundle = new Bundle();
bundle.putInt("list", list);
PendingIntent stopIntent = PendingIntent.getService(context, 0, mIntent, 0) ;
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
0, new Intent(getApplicationContext(), MainActivity.class)
.putExtras(bundle), PendingIntent.FLAG_UPDATE_CURRENT);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
notification = new Notification();
notification.tickerText = station.getRadioName();
notification.icon = R.mipmap.ic_launcher;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.setLatestEventInfo(getApplicationContext(),
station.getRadioName(), null, pi);
} else {
notification = new NotificationCompat.Builder(context)
.setContentTitle(getResources().getString(R.string.app_name))
.setContentText(station.getRadioName())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(
BitmapFactory.decodeResource(
context.getResources(),
R.mipmap.ic_launcher))
.addAction(myIconId,"STOP", stopIntent)
.setOngoing(true).setContentIntent(pi).build();
}
startForeground(NOTIFICATION_ID, notification);
}
这是我的 OnStartCommand:
public int onStartCommand(Intent intent, int flags, int startId) {
task = new ProgressTask();
task.execute();
return START_NOT_STICKY;
}
我使用了 Intent 和 PendingIntent 来启动服务,但是如何使用 PendingIntent 将服务设置为 stopSelf() ? 我被困在这个问题上好几天了,提前感谢您的帮助。
最佳答案
在你的 OnStartCommand 中使用这个
if(intent.getAction().equals("STOP"))
stopSelf();
关于java - 使用 PendingIntent 停止服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34427215/