Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 使用檔案進行跨進程通訊(IPC)的完整示範

編輯:關於 Android 程式設計

一、為什麼檔案也能做 IPC

談到 Android 的進程間通訊,大家通常會想到 Binder、Messenger、AIDL、ContentProvider 或 Socket。檔案其實也是一種可行的方式:兩個進程讀寫同一個檔案來交換資料。

這在 Windows 上會有障礙——檔案一旦加上獨佔鎖,其他線程連讀都不行。但 Android 基於 Linux,並行讀寫檔案不受這種限制,多個線程同時對同一檔案操作是被允許的(當然,這是允許而非推薦,資料競爭的風險仍然存在,實務上要自行協調讀寫時序)。

檔案方式的優點是簡單直觀,而且不只限於文字:直接把物件序列化寫入檔案,另一個進程再反序列化還原,就能傳遞完整的資料結構。

二、實作步驟

1. 資料類別實作序列化介面

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);
    }
}

2. 序列化寫入檔案

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();
}

3. 另一個進程反序列化

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();
}

4. 在 Manifest 中開啟多進程

關鍵就是 android:process 屬性,冒號開頭代表這是應用私有的進程:

<activity android:name=".SecondActivity"
    android:process=":remote" />

三、完整小案例

MainActivity 布局

<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>

SecondActivity 布局

<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";
}

SecondActivity:從檔案還原物件

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();
    }
}

MainActivity:寫入物件

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();
    }
}

AndroidManifest.xml

<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>

四、什麼時候該用檔案 IPC

檔案方式的定位其實相當明確:適合「寫一次、讀很多次」、「資料量不大」、「對即時性沒有嚴格要求」的情境,例如把設定或快取從主進程傳給背景服務進程。它並不適合高頻、低延遲的通訊——那類需求請用 AIDL 或 Messenger。

三個實務上的注意事項:Android 6.0 以後存取外部儲存空間需要動態請求 READ/WRITE_EXTERNAL_STORAGE 權限,兩個進程都要有;寫入建議採用「先寫暫存檔、完成後 rename」的方式,避免讀取端拿到寫到一半的檔案;若追求更好的效能與更低的使用門檻,SharedPreferences 的 MODE_MULTI_PROCESS 曾經是選項,但它在 API 23 之後已被標記為不可靠,不宜再用。

完整專案:IPCDemo

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved