我的解決方法是將文件保存的URI SharedPreferences和的onResume恢復。
我遇到過同樣的情況:我有一張照片列表,並在照片列表中按一個相框將調用android本機相機應用拍攝照片。有時(如使用率的2%)從Android本機相機應用程序返回時,圖片不會按預期顯示在相框中。我感到困惑,無法弄清楚發生了什麼。直到我的一位同事在「開發者選項」中設置「不保留活動」,並且始終遇到錯誤,我才知道這是一個活動被殺的問題。
下面是一些代碼來說明我的解決方案:
public static class PhotoOnClickListener implements OnClickListener {
...
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
activity.fileUri[index] = getOutputMediaFileUri(MEDIA_TYPE_IMAGE, "xxxxxx");
activity.saveKeyValue("game_photo_list_file_uri_" + index, activity.fileUri[index].toString());
intent.putExtra(MediaStore.EXTRA_OUTPUT, activity.fileUri[index]);
activity.startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
...
}
private void tryRecoverFromBeingKilledOfLowMemory() {
String s;
for (int i = 0; i < fileUri.length; i++) {
s = readKey("game_photo_list_file_uri_" + i);
if (s != null) {
fileUri[i] = Uri.parse(s);
updatePhoto(i);
}
}
}
@Override
protected void onResume() {
super.onResume();
if (readKey("from_game_main") != null) {
removeKeysPrefixedBy("game_photo_list");
removeKey("from_game_main");
removeKey("uploader_id");
}
tryRecoverFromBeingKilledOfLowMemory();
}
在代碼:
- readKey,saveKeyValue,removeKey,removeKeysPrefixedBy從CommonActivity作爲共同操作SharedPrefeneces繼承。
- 關鍵from_game_main表示當前恢復正常,應該從空的照片列表開始。 GameMainActivity中的關鍵字from_game_main在startActivity之前保存。換句話說,目前的恢復是從低記憶力中恢復過來的。
希望它有幫助。