音楽を再生するサービスと、サービスと対話するための GUI を提供するアクティビティがあります。アクティビティは、リスト項目のクリック (録音のリストがあります) で開き、onCreate() メソッドでサービスをバインド (および作成) します。 .
onDestroy() が呼び出されると、サービスのバインドを解除します (これによりサービスが破棄されます)。アクティビティが終了した場合にサービスを実行したくないので、これで問題ありませんが、再作成されるため、方向の変更時に問題が発生します。再びアクティビティとサービスも (デバイスを回転させると、トラックが停止され、最初から再生されます)。
役に立つかもしれないいくつかのフラグ (orientationChange) について知っていますが、ランドスケープで別のレイアウトが必要なので、私にとっては良い習慣ではありません。また、アプリが実行されている限り音楽プレーヤー サービスを実行することもできますが、ユーザーはプレーヤーを開きたくなく、単に録音したいだけなので、プレーヤー サービスが必ずしもここにあるとは限りません。 .
以下にいくつかのコード スニペットを示します。
@Override
protected void onCreate(Bundle savedInstanceState) {
LocalBroadcastManager.getInstance(this).registerReceiver(mLocalReceiver, new IntentFilter(PlayerBroadcastReceiver.ACTION_PLAYER_SERVICE_STARTED));
setContentView(R.layout.media_player_screen);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
AudioPlayerServiceBridge.getInstance().addCallback(this);
AudioPlayerServiceBridge.getInstance().doBindService(this);
init(savedInstanceState);
super.onCreate(savedInstanceState);
}
@Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mLocalReceiver);
mLocalReceiver.removeCallback();
Log.d(AudioPlayerActivity.class.getName(), "onDestroy() -> "+AudioPlayerActivity.class.getName());
AudioPlayerServiceBridge.getInstance().doUnbindService(this);
AudioPlayerServiceBridge.getInstance().removeCallback(this);
super.onDestroy();
}
およびサービス接続マネージャー:
public void doBindService(Context context) {
// Establish a connection with the service. We use an explicit
// class name because there is no reason to be able to let other
// applications replace our component.
if(!mIsBound){
context.bindService(new Intent(context,
AudioPlayerService.class), serviceConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
}
public void doUnbindService(Context context) {
if (mIsBound) {
// If we have received the service, and hence registered with
// it, then now is the time to unregister.
if (mServiceMessenger != null) {
Message msg = Message.obtain(null, AudioPlayerService.MSG_UNREGISTER_CLIENT);
msg.replyTo = mMessenger;
mServiceMessenger.send(msg);
}
// Detach our existing connection.
context.unbindService(serviceConnection);
mIsBound = false;
}
}
可能であれば、この問題を処理するための良い方法を教えてください。