[TOC]
Andorid IPC
Android中的多进程模式
1. 开启多进程模式
在Android中,开启多进程的方式是给四大组件(静态注册),加上process属性,让其运行在其他进程,默认的进程的名称为包名.
例如:
1 2 3 4 5 6 7 8 9
| <activity android:name=".MainActivity" android:process=":remote"> </activity> <activity android:name=".SecondActivity" android:process="[包名].remote" > </activity>
|
这个MainActivity将运行在包名+:remote这个名称的进程中.而SecondActivity将运行在[packageName].remote这个进程中.
二者区别:
加冒号':'这种方式是在当前进程名称前面附加上当前应用的包名,是一种简写方式;对于SecondActivity来说是完整的进程命名.此外,加冒号这种方式运行的进程是当前应用的私有进程,其他应用的组件不可以和它运行在同一个进程中,而采用完整命名的进行是全局进程,其他应用通过ShareUID方式可以和它运行在同一个进程中.
Android系统会给每个应用分配一个唯一的UID,具有相同UID的应用才能共享数据,两个应用听过ShareUID运行在同一个进程是有要求的,这两个应用必须有相同的ShareUID并且包签名相同才可以.
2. 多进程模式的运行机制
多进程所带来的问题
- 静态成员和单例完全失效
- 线程同步机制完全失效
- SharePreference的可靠性下降(SP只是做了线程同步喂)
- Application多次创建
IPC 基础概念
1. Serializable
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| public class User implements Serializable { private static final long serialVersionUID = -6081784905993904744L; private String name; private int age; private int id; public User(String name,int age,int id){ this.name = name; this.age = age; this.id = id; }
public static long getSerialVersionUID() { return serialVersionUID; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public int getId() { return id; }
public void setId(int id) { this.id = id; } }
|
序列化与反序列化User
1 2 3 4 5 6 7 8 9 10
| User user = new User("duo",20,1001); ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("test.txt")); oos.writeObject(user); oos.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt")); User user2 = (User) ois.readObject(); ois.close();
|
2. Parcelable
parcelable是Android提供的一种序列化和反序列化方式,它比Serializable效率更高一些.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
import android.os.Parcel; import android.os.Parcelable;
public class User implements Parcelable { public int id; public String name; public int age;
public User(int id, String name, int age) { this.id = id; this.name = name; this.age = age; }
protected User(Parcel in) { name = in.readString(); age = in.readInt(); id = in.readInt(); }
public static final Creator<User> CREATOR = new Creator<User>() { @Override public User createFromParcel(Parcel in) { return new User(in); }
@Override public User[] newArray(int size) { return new User[size]; } };
@Override public int describeContents() { return 0; }
@Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeInt(age); dest.writeInt(id); } }
|
3. Binder