Android 应用实现多进程

来源:互联网 发布:算法第四版 kindle 编辑:程序博客网 时间:2024/05/29 05:03
Android Service 跨进程实现:
同一个应用程序中实现多个进程通信
通信机制 :使用Aidl通信:
具体步骤:
1、新建Aidl文件 例 : IClickAidlInterface.aidl


interface IClickAidlInterface {


    String testAidl(String str) ;
}
以上步骤,如果没有差错,重新编译,会自动生成一个
IClickAidlInterface接口文件,记住一定要重新编译才会生成,


2、新建service类,我们需要启动的另外一个进程的类。RemoteService
需要再manifest文件中设置一个变量  android:process=":clickStream"
        <service
            android:name="绝对路径"
            android:enabled="true"
            android:exported="false" 
            android:process=":clickStream">
声明process则说明,此服务与我们应用的进程不在同一个进程中,


3、在service实现aidl文件中定义的接口


    private final IClickAidlInterface.Stub ClickInterface = new IClickAidlInterface.Stub() {
        @Override
        public String testAidl(String str) throws RemoteException {
            Log.v("zgy","======current pid======="+ android.os.Process.myPid()+ ",str = "+ str) ;
            return str;
        }
    }  ;
4、在service中实现onBind方法,因为IClickAidlInterface.Stub 继承之Binder ,从代码中可知Stub extends android.os.Binder
所以直接返回 ClickInterface即可


    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
       return ClickInterface;
    }
5、在需要绑定服务的地方,绑定服务即可,绑定service的方法都是通用的
这里写一个通用的方法实现绑定Servie,


/**
 * Created by moon.zhong on 2015/2/9.
 */
public class BindService {
    private IClickAidlInterface aidlInterface ;
    private static BindService instance ;
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            aidlInterface = IClickAidlInterface.Stub.asInterface(service) ;
        }


        @Override
        public void onServiceDisconnected(ComponentName name) {
            aidlInterface = null ;
        }
    } ;
    private BindService(Context context){
        context.getApplicationContext().bindService(new Intent("com.service.RemoteService"),
                mConnection, Service.BIND_AUTO_CREATE) ;
    }
    
    public static synchronized BindService newInstance(Context context){
        if(instance == null){
            instance = new BindService(context) ;
        }
        return instance ;
    }
    
    public IClickAidlInterface getAidlInterface(){
        return aidlInterface ;
    }
    
}
1 0