編輯:關於 Android 程式設計
談到 Android 的進程間通訊,大家通常會想到 Binder、Messenger、AIDL、ContentProvider 或 Socket。檔案其實也是一種可行的方式:兩個進程讀寫同一個檔案來交換資料。
這在 Windows 上會有障礙——檔案一旦加上獨佔鎖,其他線程連讀都不行。但 Android 基於 Linux,並行讀寫檔案不受這種限制,多個線程同時對同一檔案操作是被允許的(當然,這是允許而非推薦,資料競爭的風險仍然存在,實務上要自行協調讀寫時序)。
檔案方式的優點是簡單直觀,而且不只限於文字:直接把物件序列化寫入檔案,另一個進程再反序列化還原,就能傳遞完整的資料結構。
public class User implements Parcelable, Serializable {
private int userId;
private String userName;
private boolean isMale;
public User() { }
public User(int userId, String userName, boolean isMale) {
this.userId = userId;
this.userName = userName;
this.isMale = isMale;
}
@Override
public int describeContents() { return 0; }
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(userId);
dest.writeString(userName);
dest.writeInt(isMale ? 1 : 0);
}
private User(Parcel in) {
userId = in.readInt();
userName = in.readString();
isMale = in.readInt() == 1;
}
public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
@Override public User createFromParcel(Parcel source) { return new User(source); }
@Override public User[] newArray(int size) { return new User[size]; }
};
@Override
public String toString() {
return String.format("User:{userId:%s, userName:%s, isMale:%s}",
userId, userName, isMale);
}
}
private void persistToFile() {
new Thread(new Runnable() {
@Override
public void run() {
User user = new User(1, "hello world", false);
File dir = new File(MyConstants.CHAPTER_2_PATH);
if (!dir.exists()) { dir.mkdirs(); }
File cachedFile = new File(MyConstants.CACHE_FILE_PATH);
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(cachedFile));
oos.writeObject(user);
Log.d(TAG, "persist user:" + user);
} catch (IOException e) {
e.printStackTrace();
} finally {
MyUtils.close(oos);
}
}
}).start();
}
private void recoverFromFile() {
new Thread(new Runnable() {
@Override
public void run() {
File cachedFile = new File(MyConstants.CACHE_FILE_PATH);
if (!cachedFile.exists()) { return; }
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(cachedFile));
User user = (User) ois.readObject();
Log.d(TAG, "recover user:" + user);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
MyUtils.close(ois);
}
}
}).start();
}
關鍵就是 android:process 屬性,冒號開頭代表這是應用私有的進程:
<activity android:name=".SecondActivity"
android:process=":remote" />
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:fitsSystemWindows="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="File" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="open activity B" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="at activity B" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
public class MyUtils {
public static void close(Closeable closeable) {
try {
if (closeable != null) { closeable.close(); }
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class MyConstants {
public static final String CHAPTER_2_PATH =
Environment.getExternalStorageDirectory().getPath() + "/zhangmiao/charpter_2/";
public static final String CACHE_FILE_PATH = CHAPTER_2_PATH + "usercache";
}
public class SecondActivity extends Activity {
private static final String TAG = "SecondActivity";
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
mTextView = (TextView) findViewById(R.id.textView1);
}
@Override
protected void onResume() {
super.onResume();
// Intent 傳遞只能在本進程內用,跨進程時這裡拿到的可能不是最新值
recoverFromFile();
}
private void recoverFromFile() {
new Thread(new Runnable() {
@Override
public void run() {
File cachedFile = new File(MyConstants.CACHE_FILE_PATH);
if (!cachedFile.exists()) { return; }
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(new FileInputStream(cachedFile));
User user = (User) ois.readObject();
Log.d(TAG, "recover user:" + user);
mTextView.setText("recover user:" + user);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} finally {
MyUtils.close(ois);
}
}
}).start();
}
}
public class MainActivity extends AppCompatActivity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.textView1);
findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, SecondActivity.class));
}
});
}
@Override
protected void onResume() {
super.onResume();
persistToFile();
}
private void persistToFile() {
new Thread(new Runnable() {
@Override
public void run() {
User user = new User(1, "hello world", false);
File dir = new File(MyConstants.CHAPTER_2_PATH);
if (!dir.exists()) { dir.mkdirs(); }
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(new FileOutputStream(MyConstants.CACHE_FILE_PATH));
oos.writeObject(user);
mTextView.setText("persist user:" + user);
} catch (IOException e) {
e.printStackTrace();
} finally {
MyUtils.close(oos);
}
}
}).start();
}
}
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.zhangmiao.ipcdemo">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SecondActivity"
android:label="@string/app_name"
android:process=":remote" />
</application>
</manifest>
檔案方式的定位其實相當明確:適合「寫一次、讀很多次」、「資料量不大」、「對即時性沒有嚴格要求」的情境,例如把設定或快取從主進程傳給背景服務進程。它並不適合高頻、低延遲的通訊——那類需求請用 AIDL 或 Messenger。
三個實務上的注意事項:Android 6.0 以後存取外部儲存空間需要動態請求 READ/WRITE_EXTERNAL_STORAGE 權限,兩個進程都要有;寫入建議採用「先寫暫存檔、完成後 rename」的方式,避免讀取端拿到寫到一半的檔案;若追求更好的效能與更低的使用門檻,SharedPreferences 的 MODE_MULTI_PROCESS 曾經是選項,但它在 API 23 之後已被標記為不可靠,不宜再用。
完整專案:IPCDemo
Android 解析度適配完全指南:dp、dpi 與資源目錄怎麼用
解析度適配是 Android 長年被詬病的問題之一。本文依官方文件 Supporting Multiple Screens 的脈絡,把核心概念與實務技巧整理成一份可操作的
Android 屏幕適配五種方案詳解:從像素密度到權重布局
什麼是屏幕適配 所謂適配,就是讓同一個應用在不同的手機上呈現一致的視覺效果。動手之前,第一步永遠是先確認當前設備屬於哪一檔像素密度(xhdpi、hdpi、mdpi 等)。
徹底搞懂 Android layout_weight 的分配規則
layout_weight 是使用 LinearLayout 時幾乎必備的屬性,但它的行為有個反直覺之處,讓不少人第一次用時都栽了跟頭。搞懂背後的計算方式,之後排版會順手
微信朋友圈熱文在哪?微信朋友圈熱文查看方法
微信朋友圈熱文查看方法 新版微信在搜索入口中加入了朋友圈熱文功能,可以查看近期熱門文章。 打開微信,進入通訊錄或搜索頁面,點擊搜索欄。 在搜索頁面即可看到朋友圈熱文入