I am having a problem with my Android service and client apps who rebind to it. Everything works fine when a client app initially binds to my service, after which messages can be sent from service to client. However, if the client app is killed and then binds agains, onRebind() is correctly called in the service, but my messenger in the intent is invalid, causing a DeadObjectException, as noted in the code below. Any ideas?
Here is my code for the service:
@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);
}
}
And here is the code for the application:
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);