編輯:關於 Android 開發
共享文件是一種簡單實用的進程間通信方式:兩個進程通過讀寫同一個文件交換數據。在 Windows 上,文件一旦被加上獨佔鎖,其他線程連讀都無法進行;而 Android 基於 Linux,對文件的並發讀寫沒有這類限制,甚至兩個線程同時讀寫同一個文件也是允許的——當然,這並不意味著不會出問題,需要業務上自行保證一致性。
通過文件交換數據的好處是靈活:除了交換文本信息,還可以把對象序列化寫入文件,再由另一個進程反序列化還原。
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)。
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();
}
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();
}
<activity android:name=".SecondActivity" android:process=":remote" />
:remote 表示該 Activity 運行在一個私有進程中,與主進程隔離。
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";
}
<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>
<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>
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() { /* 同上 */ }
}
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() { /* 同上 */ }
}
<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 及以上還要處理動態授權。
Android WindowManager 深入解析與浮動視窗安全風險探討
Android WindowManager 深入解析與浮動視窗安全風險探討 前陣子在網路上看到有人在討論一個攻擊手法:應用可以開啟一個背景 Service,持續偵測目前最
仿 QQ 好友列表左滑選單:SwipeMenuListView 置頂與刪除實作
帶手勢的列表選單,不用自己刻 先看一下要做的效果——列表項向左滑出「置頂/刪除」按鈕: SwipeMenuListView 是 GitHub 上的第三方開源專案(專案網
Android 6.0 動態權限管理方案
Android 6.0 動態權限管理方案 Android 6.0 引入動態權限機制,使用者在執行階段可決定是否授予相機、錄音、定位等敏感權限。這提升隱私控制,但也要求開發
cocos2d-x 核心架構入門:Director、Scene 與 Layer(一)
cocos2d-x 核心架構入門:Director、Scene 與 Layer(一) 本文整理自官方文檔,介紹 cocos2d-x 遊戲開發中最基礎的三個核心概念:Dir