如何在 exit/pause 应用程序时暂停背景音乐服务?

How to pause background music service when you exit/pause the application?

我想在用户玩游戏时播放背景音乐。音乐在用户启动应用程序时开始播放,在用户离开时暂停,在用户返回应用程序时继续播放。

我尝试使用 this method,我对其进行了一些编辑:

public class MainActivity extends Activity {

    private boolean bounded;
    private BackgroundSoundService backgroundSoundService;

    ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceDisconnected( ComponentName name ) {
            bounded = false;
            backgroundSoundService = null;
        }

        @Override
        public void onServiceConnected( ComponentName name, IBinder service ) {
            bounded = true;
            BackgroundSoundService.LocalBinder localBinder = (BackgroundSoundService.LocalBinder) service;
            backgroundSoundService = localBinder.getServiceInstance();
        }
    };

    @Override
    public void onCreate( Bundle savedInstanceState ) {
        super.onCreate(savedInstanceState);
        // (code that's not necessary)

        backgroundSoundService.start(); // this is where the error is thrown
    }

    @Override
    public void onPause() {
        super.onPause();

        backgroundSoundService.pause();
    }

    @Override
    public void onResume() {
        super.onResume();

        backgroundSoundService.resume();
    }

    @Override
    public void onStop() {
        super.onStop();

        backgroundSoundService.pause();
    }

    @Override
    public void onStart() {
        super.onStart();

        Intent intent = new Intent(this, BackgroundSoundService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);

        backgroundSoundService.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        backgroundSoundService.destroy();
    }
}

我使用 activity 来播放、暂停和恢复背景音乐。对于这个问题,我将在此处省略不必要的 methods/lines:

public class BackgroundSoundService extends Service {
    private static final String TAG = null;
    public IBinder binder = new LocalBinder();

    public IBinder onBind( Intent arg0 ) {
        return binder;
    }

    public IBinder onUnBind( Intent arg0 ) {
        return null;
    }

    public class LocalBinder extends Binder {
        public BackgroundSoundService getServiceInstance() {
            return BackgroundSoundService.this;
        }
    }
}

但是,当我 运行 应用程序时,我在 MainActivity class 中得到一个 NullPointerException (在 onCreate 方法中,我在代码)。

变量似乎还没有初始化,但我确实需要在用户打开应用程序时启动音乐。

我还尝试从 onCreate 方法中删除 backgroundSoundService.start();,这样当 onStart 被调用时音乐就会开始。但是,当我这样做时,我得到了同样的错误。

那么,在调用其方法之前如何初始化 backgroundSoundService

首先从 onCreate 中删除此 backgroundSoundService.start() 并将其添加到 onServiceConnected() 方法中

你需要在做任何与 backgroundSoundService 相关的事情之前检查 null,如下所示

 @Override
    public void onPause() {
        super.onPause();
        if(backgroundSoundService != null){
           backgroundSoundService.pause();
        }
    }

backgroundSoundService

的所有外观中添加这种空检查