Search code examples
androidandroid-studioonactivityresult

Camera does not return to main activity after taking picture


When the main activity starts it directly starts the intent for MediaStore.ACTION_IMAGE_CAPTURE I implemented the onActivityResult method, but when I take a picture it does not return back to the main activity, rather it remains in the camera app

This is the code:

final int REQUEST_TAKE_IMAGE = 1;

    ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = findViewById(R.id.imageView);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_TAKE_IMAGE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_TAKE_IMAGE){
            if(resultCode == RESULT_OK){
                assert data != null;
                Bundle extras = data.getExtras();
                assert extras != null;
                Bitmap bitmap = (Bitmap) extras.get("data");
                imageView.setImageBitmap(bitmap);
            }
        }
    }

Solution

  • Try shifting the intent launch to a button click listener, my guess what is happening is whenever your activity starts, it takes the person back to the camera app as intent is launched on start and activity uses this callback every time you try to bring it to the foreground,i.e, taking a pick and expecting it to bring you back to the activity.