Androud7.0之IPC机制(多进程、及其通信)

来源:互联网 发布:cooledit有mac版 编辑:程序博客网 时间:2024/06/14 10:46

IPC(Inter-Process Communication)为进程间通信或者跨进程通信,是指两个进程之间进行数据交换的过程。

Android开启多进程模式

<activity    android:process = "你的进程名"/>

只需要在四大组件中添加 android:process 就可为其新建一个进程。

但Android中的多进程会导致

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

IPC的实现

Serializable接口

只需要对类实现Serializable接口就可以。

public class Book implements Serializable{    private static final long serialVersionUID = 5343563234354645L;    public int ID;    public String Book_Name;}

而对象的序列化和反序列化如下

//序列化Book book = new Book();ObjectOutputStream  out = new ObjectOutputStream( new FileOutputStream("cache.txt"));out.writeObject(book);out.close();//反序列化ObjectInputStream in = new ObjectInputStream(new FileInputStram("cache.txt"));User newUser = (User)in.readObject();in.close();

Parcelable接口

package ll.aidl;import android.os.Parcel;import android.os.Parcelable;/** * Created by 95112 on 8/28/2017. */public class Book implements Parcelable {    public int bookId;    public Book book;    public Book(int bookId)    {        bookId = bookId;    }    protected Book(Parcel in) {        bookId = in.readInt();        book = in.readParcelable(Thread.currentThread().getContextClassLoader());    }    public static final Creator<Book> CREATOR = new Creator<Book>() {        @Override        public Book createFromParcel(Parcel in) {            return new Book(in);        }        @Override        public Book[] newArray(int size) {            return new Book[size];        }    };    @Override    public int describeContents() {        return 0;    }    @Override    public void writeToParcel(Parcel dest, int flags) {    }}
阅读全文
0 0
原创粉丝点击