4

音楽を再生するアクティビティとサービスがあります。アクティビティの onCreate を startService にして ServiceConnection を作成しようとすると、ServiceConnection の onServiceConnected でサービスを初期化するので、この後は null ではありません。次に、Service をこの serviceConnection にバインドします。

したがって、私の musicService は null ではなく、アプリケーションは動作し、サービスはフォアグラウンド通知を送信できます。デバイスを回転させ、画面を回転させたとします。私のアクティビティは onDestroy を呼び出し、onCreate を呼び出します。私の musicService は引き続き再生されますが、onCreate には startService があり、ServiceConnection と bindService が再び作成され、null musicService が原因でアプリケーションがクラッシュします。

ServiceConnection の onServiceConnected が呼び出されないことが原因であることを明らかにしました。最初のアクティビティ開始時に作成した musicService に接続するにはどうすればよいですか?

すべてのonCreateで実行される私のコード:

    Intent intent = new Intent(this, MusicPlaybackService.class);
    startService(intent);
    serviceConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            LocalBinder binder = (LocalBinder) service;
            musicPlaybackService = binder.getService(); 
        }

        public void onServiceDisconnected(ComponentName arg0) {
        }
    };
    bindService(intent, serviceConnection, 0);
4

1 に答える 1

1

何をしたかわかりませんが、うまくいきます。今、私はこのコードを持っています。

    Intent intent = new Intent(this, MusicPlaybackService.class);
    MyApplication.getAppContext().startService(intent);
    serviceConnection = new ServiceConnection() {

        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            LocalBinder binder = (LocalBinder) service;
            musicPlaybackService = binder.getService();
            // now onServiceConnected calls on screen rotation.
        }

        public void onServiceDisconnected(ComponentName arg0) {
        }
    };
    MyApplication.getAppContext().bindService(intent, serviceConnection, BIND_AUTO_CREATE);
于 2012-12-16T19:04:49.127 に答える