退出/暂停应用程序时如何暂停背景音乐服务?

问题描述 投票:1回答:1

我希望在用户玩游戏时播放背景音乐。当用户启动应用程序时音乐开始,当他们离开应用程序时暂停,并在返回应用程序时恢复。

我尝试使用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();
    }
}

我使用活动来播放,暂停和恢复背景音乐。我将在这里省略这个问题的不必要的方法/行:

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;
        }
    }
}

但是,当我运行应用程序时,我在NullPointerException类中获得了MainActivity(在onCreate方法中,我在代码中对其进行了评论)。

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

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

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

java android android-activity android-service android-service-binding
1个回答
1
投票

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

你需要在做任何与backgroundSoundService相关的事情之前检查null

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

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

© www.soinside.com 2019 - 2024. All rights reserved.