我的解决方法是将文件保存的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之前保存。换句话说,目前的恢复是从低记忆力中恢复过来的。
希望它有帮助。