onActivityResult not called after taking a photo in Android

后端 未结 3 681
终归单人心
终归单人心 2020-12-10 19:44

I am using this code but my onActivityResult never gets called. I used to make the request without passing the extra intent to save the image to an SD card and that worked f

相关标签:
3条回答
  • 2020-12-10 20:06

    I use something like this and it works fine:

    public class MainActivity extends Activity implements OnClickListener {
    
    Button btnTackPic;
    Bitmap bitMap;
    static int TAKE_PICTURE = 1;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        // Setup camera ready for picture clicking
    
        // add onclick listener to the button
        btnTackPic.setOnClickListener(this);
    
    }
    
    // Take pic
    @Override
    public void onClick(View view) {
    
        // create intent with ACTION_IMAGE_CAPTURE action 
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    
        // start camera activity
        startActivityForResult(intent, TAKE_PICTURE);
    
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    
        if (requestCode == TAKE_PICTURE && resultCode== RESULT_OK && intent != null){
            // get bundle
            Bundle extras = intent.getExtras();
    
            // get bitmap
            bitMap = (Bitmap) extras.get("data");
        }
    }
    

    }

    0 讨论(0)
  • 2020-12-10 20:07

    In my case, the onDestroy called instead. Because android system will try to release memory (if our apps in background, and we open camera apps), and the reason it never called onActivityResult method also due to this please make sure you were not using noHistory=true or intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)

    e.g

    // AbcActivity.kt
    val intent = Intent(AbcActivity.this, RegistrationForm.class)
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
    startActivity(intent)
    
    // RegistrationForm.kt
    val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    // do take pictures, and confirm the photo, never going back to the RegistrationForm, instead back to AbcActivity
    

    by removing flags and noHistory=true (in AndroidManifest.xml) my activity recreated and onActivityResult called again, but we need to save the previous state using ViewModel or (onSaveInstance & onRestoreInstance)

    0 讨论(0)
  • 2020-12-10 20:16

    I needed to add this:

        photo.getParentFile().mkdirs();
        photo.createNewFile();
    

    I believe the reason it was failing was because the file I was trying to write the image to didn't exist.

    0 讨论(0)
提交回复
热议问题