Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

android - Activity killed / onCreate called after taking picture via intent

I am trying to take a picture using an intent. My problem is that sometimes after taking a picture my activity, which calls startActivityForResult, seems to be destroyed so that onCreate is called again.

Here is my code for taking pictures after clicking an imageview, which image should be replaced:

if (!getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            Util.makeLongToast(R.string.lang_no_camera);
        } else {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, TAKE_ITEM_PHOTO);
        }

...

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.v(TAG, "onactivityresult called");
    if (requestCode == TAKE_ITEM_PHOTO) {
        if (data != null) {

            imageUri = data.getData();


                try {
                    img_photo.setImageBitmap(Media.getBitmap(
                            getContentResolver(), imageUri));
            } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

        } else
            Log.w(TAG, "data is null");
    }
}

So all i try is to take a picture and replace the image of an imageview with it. But in some cases onCreate is called after onActivityResult was called and the new image is lost.

Help is greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Actually the camera causes the orientation change in your activity that is why your activity is being destroyed and recreated.

Add this in your manifest file it will prevent the orientation change and your activity will not get destroyed and recreated.

<activity
    android:name=".YourActivity"
    android:configChanges="orientation|keyboardHidden|screenSize"
    android:screenOrientation="portrait" >
</activity>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...