使用服务和信使管理两个应用之间的通信

时间:2016-05-04 14:25:05

标签: android service messenger

我想开发两个应用程序。我需要一个能够启动和停止第二个应用程序的应用程序。为此,我使用服务在这两个应用程序之间设置了一个信使。该服务坚持第二个应用程序。

我在app1中初始化了这样的意图:

protected void onCreate()
{
    super.onCreate();
    Intent mIntent = new Intent();
    mIntent.setAction("com.package.service");
    bindService(mIntent, mServiceConnection, BIND_AUTO_CREATE);

} 
private ServiceConnection mServiceConnection = new ServiceConnection() {

    @Override
    public void onServiceDisconnected(ComponentName arg0) {

        mIsBinded=false;
        mServiceConnection=null;
    }

    @Override
    public void onServiceConnected(ComponentName arg0, IBinder arg1) {

        mIsBinded=true;
        mMessenger = new Messenger(arg1);
    }
};

我发送消息以关闭app2。

在app2中我有这样的服务:

public class RemoteServiceClient extends Service
{
static final int STOP = 0;
static final int CONTINUE = 1;
private static final String TAG ="service" ;

class MyHandler extends Handler
{

    @Override
    public void handleMessage(Message msg) {
        // TODO Auto-generated method stub
        super.handleMessage(msg);
        switch(msg.what)
        {
            case STOP:
                sendBroadcast(new Intent("stop"));
                Log.d(TAG,"stopapp");
                break;
            case CONTINUE:
                break;
        }
    }
}
Messenger mMessenger = new Messenger(new MyHandler());
@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return mMessenger.getBinder();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    //TODO do something useful
    return Service.START_STICKY;
}

}

我还在应用程序中放入了清单:

<service android:name="com.package.app.service"
        android:process=":exported">
        <intent-filter>
            <action android:name="com.package.service" />
        </intent-filter>
    </service>

在app2的活动中我放了一个braodcast接收器,当消息STOP传递时,app调用finish()。

我遇到的问题是第一次消息传递消息并重新启动app2。一旦app2重新启动,app1就无法再次停止app2。我收到这个错误:

05-04 15:47:28.168 16741-16755/com.package.app1 W/System.err: android.os.DeadObjectException
05-04 15:47:28.178 16741-16755/com.package.app1 W/System.err:     at android.os.BinderProxy.transact(Native Method)

0 个答案:

没有答案