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

用共享文件實現 Android 進程間通信:序列化對象的完整示例

編輯:關於 Android 開發

一、為什麼可以用文件做 IPC

共享文件是一種簡單實用的進程間通信方式:兩個進程通過讀寫同一個文件交換數據。在 Windows 上,文件一旦被加上獨佔鎖,其他線程連讀都無法進行;而 Android 基於 Linux,對文件的並發讀寫沒有這類限制,甚至兩個線程同時讀寫同一個文件也是允許的——當然,這並不意味著不會出問題,需要業務上自行保證一致性。

通過文件交換數據的好處是靈活:除了交換文本信息,還可以把對象序列化寫入文件,再由另一個進程反序列化還原。

二、實現步驟

1. 數據類同時實現 Parcelable 與 Serializable

public class User implements Parcelable, Serializable {
    public static int sUserId = 1;
    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);
    }
}

之所以兩個接口都實現,是因為後續既要用 Intent 傳對象(Serializable),也要寫入文件(同樣依賴 Serializable)。

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 objectOutputStream = null;
            try {
                objectOutputStream = new ObjectOutputStream(new FileOutputStream(cachedFile));
                objectOutputStream.writeObject(user);
                Log.d(TAG, "persist user:" + user);
                mTextView.setText("persist user:" + user);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                MyUtils.close(objectOutputStream);
            }
        }
    }).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 objectInputStream = null;
            try {
                objectInputStream = new ObjectInputStream(new FileInputStream(cachedFile));
                User user = (User) objectInputStream.readObject();
                Log.d(TAG, "recover user:" + user);
                mTextView.setText("recover user:" + user);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } finally {
                MyUtils.close(objectInputStream);
            }
        }
    }).start();
}

4. 在 AndroidManifest.xml 中開啟多進程

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

:remote 表示該 Activity 運行在一個私有進程中,與主進程隔離。

三、完整示例

MyUtils 與 MyConstants

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

activity_main.xml

<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"
        android:text="A"/>
</LinearLayout>

activity_second.xml

<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"
        android:text="Activity B"/>
</LinearLayout>

MainActivity

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                intent.putExtra("extra_user", (Serializable) new User(0, "jake", true));
                startActivity(intent);
            }
        });
        mTextView = (TextView) findViewById(R.id.textView1);
    }

    @Override
    protected void onResume() {
        super.onResume();
        persistToFile();      // 主進程寫入
    }

    private void persistToFile() { /* 同上 */ }
}

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();
        User user = (User) getIntent().getSerializableExtra("extra_user");
        Log.d(TAG, "user:" + user);
        recoverFromFile();    // 另一進程讀取
    }

    private void recoverFromFile() { /* 同上 */ }
}

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:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity"
            android:label="@string/app_name"
            android:launchMode="standard"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".SecondActivity"
            android:configChanges="screenLayout"
            android:label="@string/app_name"
            android:process=":remote" />
    </application>
</manifest>

四、實踐注意事項

  • 訪問外部存儲需要申請 WRITE_EXTERNAL_STORAGE 權限,Android 6.0 及以上還要處理動態授權。
  • 文件方式的可靠性不高:寫入過程中若進程被殺,可能留下半個文件導致反序列化失敗,重要數據需要加校驗或採用其他 IPC 方案。
  • 若需要更規範、更高性能的跨進程通信,可考慮 AIDL、Messenger、ContentProvider 或 Binder,文件方式更適合簡單、低頻的數據交換場景。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved