我的 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);