2. IPC机制

作者: 詹徐照 | 来源:发表于2018-04-14 21:43 被阅读36次
IPC机制.png
脑图链接:http://naotu.baidu.com/file/ac4586250dc8e89909b6021acbe81faf?token=547626ceb7336446

2.1 Android IPC简介

线程与进程
线程是CPU调度的最小单元。
进程一般指一个执行单元,在PC和移动设备上只一个程序或者一个应用。
一个进程可以包含多个线程。

2.2 Android中的多进程模式

2.2.1 开启多进程模式

不考虑通过JNI在native层去fork新进程这种特殊方法的情况下,
在Android中使用多进程只有一种方法,那就是给四大组件在Menifest中指定 android:process属性。

2.2.2 多进程模式的运行机制

Android会为每个进程都分配一个独立的虚拟机,不同的虚拟机在内存分配上有不同的地址空间,这就导致在不同的虚拟机中访问同一个类对象会产生多份副本。
所有运行在不同进程中的四大组件,只要他们之间需要通过内存来共享数据,都会共享失败。
使用多进程会造成如下几方面的问题:

  1. 静态成员和单例模式完全失效。
  2. 线程同步机制完全失效。
  3. SharedPreferences的可靠性下降。
  4. Application会多次创建。

跨进程通讯方式
Intent传递数据
共享文件
SharedPreferences
基于Binder的Messenger和AIDL
Socket

2.3 IPC基础概念介绍

Serializable和Parcelable接口可以完成对象的序列化过程。、

静态成员变量属于类不属于对象,所以不参与序列化过程;
用transient关键字标记的成员变量不参与序列化过程;

2.3.1 Serializable接口

private static final long serialVersionUID = 1231231231231242L;
serialVersionUID如果不手动指定,系统会计算当前类的hash值复制给它,如果类发生变化,serialVersionUID就会改变,导致反序列化失败。
手动指定serialVersionUID可以很大程度的减少此种情况的发生。

2.3.2 Parcelable接口

public @ContentsFlags int describeContents();

/**
 * Flatten this object in to a Parcel.
 * 
 * @param dest The Parcel in which the object should be written.
 * @param flags Additional flags about how the object should be written.
 * May be 0 or {@link #PARCELABLE_WRITE_RETURN_VALUE}.
 */
public void writeToParcel(Parcel dest, @WriteFlags int flags);

/**
 * Interface that must be implemented and provided as a public CREATOR
 * field that generates instances of your Parcelable class from a Parcel.
 */
public interface Creator<T> {
    /**
     * Create a new instance of the Parcelable class, instantiating it
     * from the given Parcel whose data had previously been written by
     * {@link Parcelable#writeToParcel Parcelable.writeToParcel()}.
     * 
     * @param source The Parcel to read the object's data from.
     * @return Returns a new instance of the Parcelable class.
     */
    public T createFromParcel(Parcel source);
    
    /**
     * Create a new array of the Parcelable class.
     * 
     * @param size Size of the array.
     * @return Returns an array of the Parcelable class, with every entry
     * initialized to null.
     */
    public T[] newArray(int size);
}

Serilizable Parcelable对比
Serilizable是java的序列化接口,使用简单,开销大。
Parcelable是Android序列化接口,使用复杂(IDE自动生成就问题不大了),开销小,推荐使用。
Parcelable主要用在内存序列化上,本地存储、网络传输稍显复杂,建议使用Serializable。

2.3.3 Binder

Binder是Android中的一个类,实现了IBinder接口。
从IPC角度来说,Binder是Android中的一种跨进程通信方式,Binder还可以理解为一种虚拟的物理设备,他的设备驱动是/dev/binder,该通信方式在Linux中没有;
从Android Framwork角度来说,Binder是ServiceManager连接各种Manager(ActivityManager、WindowManager,等等)和响应ManagerService的桥梁;
从Android应用层来说,Binder是客户端和服务端进行通信的媒介,当bindService的时候,服务端会返回一个包含了服务端业务调用的Binder对象,通过这个Binder对象,客户端就可以获取五福短提供的服务或者数据,这里的服务包括普通服务和基于AIDL的服务。

相关文章

网友评论

    本文标题:2. IPC机制

    本文链接:https://www.haomeiwen.com/subject/wlrrkftx.html