音楽を再生するアクティビティとサービスがあります。アクティビティの 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);