Android サービスとそれに再バインドするクライアント アプリに問題があります。クライアント アプリが最初にサービスにバインドされた後、サービスからクライアントにメッセージを送信できるようになると、すべてが正常に機能します。ただし、クライアント アプリが強制終了されて再度バインドされると、サービスで onRebind() が正しく呼び出されますが、インテント内のメッセンジャーが無効であり、以下のコードに示すように DeadObjectException が発生します。何か案は?
サービスのコードは次のとおりです。
@Override
public IBinder onBind(Intent intent)
{
getMessenger(intent);
return _inputMessenger.getBinder();
}
@Override
public void onRebind(Intent intent)
{
getMessenger(intent);
}
@Override
public boolean onUnbind(Intent intent)
{
return true;
}
private void getMessenger(Intent intent)
{
Bundle extras = intent.getExtras();
if (extras != null)
{
// Get the messenger sent from the app.
// This is handled correctly after onBind() and onRebind().
_outputMessenger = (Messenger) extras.get("MESSENGER");
Log.i(TAG, "Got messenger from app: " + _outputMessenger);
}
}
private void sendMessageToClient(String key, String value)
{
Message message = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString(key, value);
message.setData(bundle);
try
{
_outputMessenger.send(message); // EXCEPTION OCCURS HERE AFTER onRebind()
}
catch (Exception ex)
{
Log.e(TAG, "_outputMessenger.send() failed: " + ex);
}
}
アプリケーションのコードは次のとおりです。
Intent intent = new Intent("com.foobar.service");
// Create a new messenger for the communication from service to app.
_messenger = new Messenger(new ServiceToActivityHandler());
intent.putExtra("MESSENGER", _messenger);
_serviceConnection = new MyServiceConnection();
_isBoundToService = _context.bindService(intent,
_serviceConnection,
Context.BIND_AUTO_CREATE);