使用文件共享也是不错的进程间通信方式,两个进程通过读/写同一个文件来交换数据。
在 Windows 系统,文件会被加排斥锁导致其他线程无法对其访问,而 Android 是基于 Linux 系统,所以并发读写文件没有限制。
// 序列化
private void persistToFile() {
new Thread(new Runnable() {
@Override
public void run() {
User user = new User(1, "wshunli", true);
File dir = new File(getApplicationContext().getCacheDir().getPath() + "/user/");
if (!dir.exists()) {
dir.mkdirs();
}
File cachedFile = new File(dir.getPath() + "/usercache");
ObjectOutputStream objectOutputStream = null;
try {
objectOutputStream = new ObjectOutputStream(
new FileOutputStream(cachedFile));
objectOutputStream.writeObject(user);
Log.d(TAG, "persist user:" + user);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (objectOutputStream != null) {
objectOutputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
}
// 反序列化
private void recoverFromFile() {
new Thread(new Runnable() {
@Override
public void run() {
User user = null;
File dir = new File(getApplicationContext().getCacheDir().getPath() + "/user/");
File cachedFile = new File(dir.getPath() + "/usercache");
if (cachedFile.exists()) {
ObjectInputStream objectInputStream = null;
try {
objectInputStream = new ObjectInputStream(
new FileInputStream(cachedFile));
user = (User) objectInputStream.readObject();
Log.d(TAG, "recover user:" + user);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (objectInputStream != null) {
objectInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}).start();
}
这样对共享文件格式没有要求,但是在多线程情况下可能导致读出的内容不是最新的。
所以文件共享适合对数据同步要求不高的进程间进行通信,并妥善地处理好并发读/写问题。
而对于 SharedPreferences 有一定的读/写缓存策略,在内存中会有一份缓存,因此在多进程情况下,系统对其的读/写就变得不可靠,所以在进程间通信时,一般不用 SharedPreferences 。
参考资料
《Android开发艺术探索》 -- 2.4.2 使用文件共享
评论 (0)