Android进程中通信的方式


     本文来自http://blog.csdn.net/liuxian13183/ ,引用必须注明出处!

大的方向上

第一、使用进程共享的方式,往往使用android:process=remote,这样开启一个新的进程,使得所有进程都可以访问这个进程,使服务可以在多进程共享;而android:process=:remote相当于给当前进程一个私有进程,用来维护其自身的业务处理。开启新进程可以用在activity、service、broadcastReceiver、ContentProvider等组件。

If the name assigned to this attribute begins with a colon (':'), a new process, private to the application, is created when it's needed and the service runs in that process.  If the process name begins with a lowercase character, the service will run in a global process of that name, provided that it has permission to do so. This allows components in different applications to share a process, reducing resource usage.

第二、使用广播的方式,可以设置category、component、package来区别广播,同时使用自定义权限来做限制

方法1、使用AIDL的方式进行

第三、使用Message+Binder

第四、使用Socket

第五、共享内存,如ContentProvider

linux有管道(Pipe)、信号(Signal)、报文(Message)、跳跃(Trace),其次信号量(Semaphore)、ShareMemory

Binder能支持跨进程通信的原因,是它实现IBinder接口,系统定义实现此接口即赋予进程通信的功能。

优势:做数据拷贝只用一次,则Pipe、Socket都需要两次;其次安全性高,不会像Socket会暴露地址,被人替换;

通信机制:Service向ServiceManager注册,得到虚拟的Uid和Pid;Client向ServiceManager请求,得到虚拟的Uid和Pid,以及目标对象的Proxy,底层通过硬件协议传输,使用Binder通讯。

通信时Client手持Proxy,ServiceManger进行转换,调用到Service。三者运行在三个独立进程中。Client/Sever全双工,互为Sever/Client

获得进程是否位于前台:

    public static boolean isRunningForeground(Application application) {
        ActivityManager activityManager = (ActivityManager) application.getSystemService("activity");
        List appProcessInfos = activityManager.getRunningAppProcesses();
        Iterator var3 = appProcessInfos.iterator();
        ActivityManager.RunningAppProcessInfo appProcessInfo;
        do {
            if (!var3.hasNext()) {
                return false;
            }
            appProcessInfo = (ActivityManager.RunningAppProcessInfo) var3.next();
        }
        while (appProcessInfo.importance != 100 || !appProcessInfo.processName.equals(application.getApplicationInfo().processName));
        return true;
    }


猜你喜欢

转载自blog.csdn.net/liuxian13183/article/details/56830789
今日推荐