android - 调用 stopForeground 导致重启当前服务

标签 android android-service android-mediaplayer

我使用通知 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/

相关文章:

java - 与EditText冲突: Watcher to the View + Observer to the MutableLiveData

java - 一行代码我看不懂

android - 如何从 Android 服务保存数据?

java - Android MediaPlayer错误反馈

java - 如何停止媒体播放器中的可运行程序?

android - 通过 Wi-Fi 运行/安装/调试 Android 应用程序?

android - 如何从字符串动态更改 ImageView 源? (Xamarin 安卓)

android - 使用 android.app.ServiceConnectionLeaked 在模拟器中获取 android 安装错误

android - 从服务捕获 NFC NDEF_DISCOVERED Intent

java - "setDataSource failed"异常