如何使用OnPause()& OnResume()在imageView中的Selected或Captured图像中

时间:2014-07-16 08:12:15

标签: android android-layout

有人可以帮助我在这段代码中使用OnPause()和OnResume()。 在imageView中保存最后选定或捕获的图像,以便当用户关闭程序并再次返回时不需要再次设置或拍摄图像。 XML文件:

          xmlns:tools="http://schemas.android.com/tools"

          android:id="@+id/LinearLayout1"

          android:layout_width="match_parent"

          android:layout_height="match_parent"

          android:orientation="vertical"

          android:padding="10dp" >

      android:layout_width="match_parent"

      android:layout_height="wrap_content"

      android:gravity="center"

      android:padding="5dp" >



<Button

        android:id="@+id/btnSelectPhoto"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:text="Select Photo" />

      android:layout_width="match_parent"

      android:layout_height="match_parent"

      android:orientation="vertical"

      android:padding="10dp" >



<ImageView

        android:id="@+id/viewImage"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:src="@drawable/camera" />

Java文件:

public class MainActivity extends Activity {
ImageView viewImage;
Button b;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b=(Button)findViewById(R.id.btnSelectPhoto);
    viewImage=(ImageView)findViewById(R.id.viewImage);
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectImage();
        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds options to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

  private void selectImage() {
    final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle("Add Photo!");
    builder.setItems(options, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (options[item].equals("Take Photo"))
            {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                startActivityForResult(intent, 1);
            }
            else if (options[item].equals("Choose from Gallery"))
            {
                Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 2);
            }
            else if (options[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == 1) {
            File f = new File(Environment.getExternalStorageDirectory().toString());
            for (File temp : f.listFiles()) {
                if (temp.getName().equals("temp.jpg")) {
                    f = temp;
                    break;
                }
            }
            try {
                Bitmap bitmap;
                BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
                        bitmapOptions); 

                viewImage.setImageBitmap(bitmap);
                String path = android.os.Environment
                        .getExternalStorageDirectory()
                        + File.separator
                        + "Phoenix" + File.separator + "default";
                f.delete();
                OutputStream outFile = null;
                File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
                try {
                    outFile = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
                    outFile.flush();
                    outFile.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (requestCode == 2) {
            Uri selectedImage = data.getData();
            String[] filePath = { MediaStore.Images.Media.DATA };
            Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePath[0]);
            String picturePath = c.getString(columnIndex);
            c.close();
            Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
            Log.w("path of image from gallery......******************.........", picturePath+"");
            viewImage.setImageBitmap(thumbnail);
        }
    }
}   

}

2 个答案:

答案 0 :(得分:0)

您必须通过将其保存在磁盘上来保留您的位图,以便(如果您的应用已被销毁)它可以在onCreate()中重新加载它。如果应用程序未被销毁,您的ImageView将具有相同的图像,因此您不必费心onResume。但我建议你先阅读:http://developer.android.com/guide/topics/data/data-storage.html

答案 1 :(得分:0)

您无法在onPause() and onResume()中处理该问题,因为如果用户onDestroy()在您的应用relaunch被调用后,系统会调用该应用onCreate(Bundle savedInstanceState)。< / p>

Lifecycle of Activity

根据您的情况,您可以使用SharedPreferences.

  1. 用户选择图片时,请存储that image's path in SharedPreference.

  2. Activity检查SharedPreference是否为空。如果它具有值(您之前存储的值),则使用该值设置图像。

  3. 有关如何使用SharedPreference的教程,你可以找到更多。只是google它。