我使用通知 ID 启动了一个前台服务,但是当我尝试调用 stopForeground(false)
时,该服务正在重新启动。但根据 android 文档,调用此方法不会停止服务。
@Override
public void onCreate() {
LogHelper.d(TAG, "onCreate");
super.onCreate();
initMediaSeesion();
}
@Override
public int onStartCommand(Intent startIntent, int flags, int startId) {
LogHelper.d(TAG, "onStartCommand");
MediaButtonReceiver.handleIntent(mSession, startIntent);
return START_STICKY;
}
public void startNotification() {
if (!mStarted) {
Notification notification = createNotification();
if (notification != null) {
mService.startForeground(NOTIFICATION_ID, notification);
mStarted = true;
}
}
}
@Override
public void pause() {
LogHelper.d(TAG, "Calling stopForeground false");
giveUpAudioFocus();
mService.stopForeground(false);
}
日志:
03-25 08:50:40.200 19564-19564/? D/MusicService: Calling stopForeground false
03-25 08:50:40.352 19564-19564/? D/MusicService: onCreate
03-25 08:50:40.475 19564-19564/? D/MusicService: onStartCommand
03-25 08:50:40.476 19564-19564/? D/MusicService: onStartCommand
最佳答案
因为您在停止服务时设置了 START_STICKY,它会自动重新启动。
这是 Android DOC 所说的
For started services, there are two additional major modes of operation they can decide to run in, depending on the value they return from onStartCommand(): START_STICKY is used for services that are explicitly started and stopped as needed, while START_NOT_STICKY or START_REDELIVER_INTENT are used for services that should only remain running while processing any commands sent to them. See the linked documentation for more detail on the semantics.
尝试使用 stopSelf();
关于android - 调用 stopForeground 导致重启当前服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36213579/