我有一个活动,打开另一个活动,以获得相机画廊图片.图片返回到我原来的活动并在imageView中休息.这工作正常.如何保存图像,以便用户稍后返回或杀死应用程序时图像仍然存在.我知道我应
活动A.
private ImageView im1; private String selectedImagePath; private static final int SELECT_PICTURE = 1; public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == SELECT_PICTURE) { Uri selectedImageUri = data.getData(); selectedImagePath = getPath(selectedImageUri); System.out.println("Image Path : " + selectedImagePath); im1.setImageURI(selectedImageUri); }}} public String getPath(Uri uri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(uri, projection, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); }; ((Button)dialogView.findViewById(R.id.button3)) .setOnClickListener(new OnClickListener() { public void onClick(View arg0) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE); }});
活动B.
Button send = (Button) findViewById(R.id.send); send.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent=new Intent(); setResult(RESULT_OK, intent); Bundle bundle=new Bundle(); bundle.putInt("image",R.id.showImg); intent.putExtras(bundle); finish(); public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { if (requestCode == SELECT_PICTURE) { Uri selectedImageUri = data.getData(); selectedImagePath = getPath(selectedImageUri); System.out.println("Image Path : " + selectedImagePath); img.setImageURI(selectedImageUri); }}} public String getPath(Uri uri) { String[] projection = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(uri, projection, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); }使用图像覆盖Activity中的onPause()方法(以了解为什么onPause,检查活动图的生命周期: http://developer.android.com/reference/android/app/Activity.html),如下所示:
@Override protected void onPause() { SharedPrefrences sp = getSharedPreferences("AppSharedPref", 0); // Open SharedPreferences with name AppSharedPref Editor editor = sp.edit(); editor.putString("ImagePath", selectedImagePath); // Store selectedImagePath with key "ImagePath". This key will be then used to retrieve data. editor.commit(); super.onPause(); }
这意味着每当此Activity进入后台时,图像路径将保存在名称为AppSharedPref的SharedPreferences中 – 此名称可以是您喜欢的任何名称,但在检索数据时需要使用相同的名称.
然后在同一个Activity中覆盖onResume()方法,以便在Activity到达前台时检索图像路径:
@Override protected void onResume() { SharedPreferences sp = getSharedPreferences("AppSharedPref", 0); selectedImagePath = settings.getString("ImagePath", ""); super.onResume(); }
您可能还想使用覆盖其他方法,例如根据图表的onStart(),但我留给您.