Activity和Service的跨进程双向通信机制

对于不同进程中的Activity和Service,要实现IPC(跨进程通信),其实就是通过IBinder接口,其中可能涉及到AIDL编程,和操作系统提供的进程通信接口这些底层c++知识。然而,Google已经为我们封装了一套Messenger机制,其底层也是使用AIDL实现的。要使用这套机制,必须为通信双方建立各自的Messenger,然后Service的Messenger依然是通过IBinder传递到Activity,Activity也可以将自己的Messenger通过Message的replyTo属性传递到Service。

Messenger使用步骤:

  1. Service需要实现一个Hanlder,用以处理从客户端收到的消息
  2. 用该Handler创建一个Messenger对象,Messenger对象内部会引用该Handler对象
  3. 用创建好的Messenger对象获得一个IBinder实例,并且将该IBinder通过Service的onBind方法返回给各个客户端
  4. 客户端通过收到的IBinder对象实例化一个Messenger对象,该Messenger内部指向指向Service中的Handler。客户端通过该Messenger对象就可以向Service中的Hanlder发送消息。
  5. Service中的Hanlder收到消息后,在Handler中的handleMessage方法中处理消息。
  6. 通过上面的第4步与第5步,就完成了客户端向Service发送消息并且Service接收到消息的单向通信过程,即客户端 -> Service。如果要实现Service向客户端回消息的通信过程,即Service -> 客户端,那么前提是在客户端中也需要像Service一样内部维护有一个指向Handler的Messenger。当在第四步中客户端向Service发送信息时,将Message的replyTo属性设置为客户端自己的Messenger。这样在第5步Service在Handler的handleMessage中处理收到的消息时,可以通过Message的Messenger再向客户端发送Message,这样客户端内维护的Handler对象就会收到来自于Service的Message,从而完成Service向客户端发送消息且客户端接收到消息的通信过程。
    综上六步就能完成客户端与Service的跨进程双向通信过程:
    客户端 -> Service -> 客户端

为了演示客户端与Service的跨进程通信,我建立了两个应用ClientApp和ServiceApp,两个应用的名称也是见名知意:

  1. ClientApp, 该App是客户端,用于调用服务
  2. ServiceApp,该App是Service端,用于供客户端ClientApp调用
    注意:跨进程通信使用Bundle,否则会报错Java.lang.RuntimeException: Can’t marshal non-Parcelable objects across processes.

客戶端demo

package com.axaet.servicecommunication;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {

private static final String TAG = "yushu";


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    textView = (TextView) findViewById(R.id.text_show);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    assert fab != null;
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Message message = Message.obtain(null, 101);
            bundle.putString("key","from MainActivity button");
            message.setData(bundle);
            message.replyTo = messenger;
            try {
                mService.send(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    });
}

String getCurProcessName(Context context) {
    int pid = android.os.Process.myPid();
    ActivityManager mActivityManager = (ActivityManager) context
            .getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
            .getRunningAppProcesses()) {
        if (appProcess.pid == pid) {
            return appProcess.processName;
        }
    }
    return null;
}

class MyHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
            case 111:
                int i = msg.arg1;
                if (i == 1) {
                    Log.i(TAG,"Main="+getCurProcessName(getApplication()));
                    Bundle bundle=msg.getData();
          Toast.makeText(MainActivity.this, "接收到Service消息"+bundle.getString("key"), Toast.LENGTH_SHORT).show();
                }
            default:
        }
    }
}

private Bundle bundle = new Bundle();
private Messenger messenger = new Messenger(new MyHandler());
private Messenger mService;
private TextView textView;
private ServiceConnection serviceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        Log.i(TAG, "onServiceConnected: ComponentName = " + name);
        mService = new Messenger(service);
        textView.setText("连接成功");
        Message message = Message.obtain(null, 101);
        bundle.putString("key","from MainActivity=11111");
        message.setData(bundle);
        message.replyTo = messenger;
        try {
            mService.send(message);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
    }
};


@Override
protected void onStart() {
    super.onStart();
    Intent intent = new Intent();
    //參數一為服務端APP包名,參數二為service的完整類名
    ComponentName name = new ComponentName("com.axaet.servicecommunication", "com.axaet.servicecommunication.MyService");
    intent.setComponent(name); //发送信息
    intent.putExtra("data", "msg from MainActivity");
    bindService(intent, serviceConnection, BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
    super.onStop();
    unbindService(serviceConnection);
}
}

服務端demo

package com.axaet.servicecommunication;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class MyService extends Service {
private static final String TAG = "yushu";
public List data = new ArrayList<>();
private Messenger mClient;

@SuppressLint("HandlerLeak")
class MyHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        switch (msg.what) {
            case 101:
                Bundle bundle=msg.getData();
                Log.i(TAG,"service="+ bundle.getString("key"));
                Log.i(TAG,"service="+getCurProcessName(getApplication()));
                Message message = Message.obtain(null, 111, 1, 1);
                bundle.putString("key","from service222222");
                message.setData(bundle);
                mClient = msg.replyTo;
                try {
                    mClient.send(message);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            default:
        }
    }
}

String getCurProcessName(Context context) {
    int pid = android.os.Process.myPid();
    ActivityManager mActivityManager = (ActivityManager) context
            .getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager
            .getRunningAppProcesses()) {
        if (appProcess.pid == pid) {

            return appProcess.processName;
        }
    }
    return null;
}

private Messenger messenger = new Messenger(new MyHandler());

public MyService() {
    data.add("This is some msg from " + TAG);
}

@Override
public IBinder onBind(Intent intent) {
    String s = intent.getStringExtra("data");
    Log.i(TAG, "onBind: 接收 " + s);
    data.add(s);
    return messenger.getBinder();
}
}

参考文章:http://blog.csdn.net/zhou114108/article/details/52050242

你可能感兴趣的:(Activity和Service的跨进程双向通信机制)