When i try to get the Uri from a picture taken wit

2019-01-20 14:45发布

问题:

here is my problem, when i try to get the Uri from the picture that I take whit the camera i get null with the camera on emulator and my device, but only whit the system camera if I use another camera app, always works. Here is my code

For launch the camera app

takePic.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    String captured_image = System.currentTimeMillis() + ".jpg";
    File file = new File(Environment.getExternalStorageDirectory(), captured_image); 
    captured_image = file.getAbsolutePath();
    outputFileUri = Uri.fromFile(file); 
    intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri); 
    intent.putExtra("return-data", true);
    startActivityForResult(intent, CAMERA_REQUEST);
   }
});

for get the image

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
  if (requestCode == CAMERA_REQUEST) { 
    ContentResolver cr = getContentResolver();
    InputStream in = null;
    try 
    {
        in = cr.openInputStream(outputFileUri); 
    } 
    catch (FileNotFoundException e) 
    {
        e.printStackTrace();
    }
  }
}

outputFileUri always have null when the activity returns. Thanks.

回答1:

Android might have killed off (and restarted) your activity before you get into onActivityResult, for instance because you rotated your device while taking the picture. Try to store and restore outputFileUri with the rest of the Activity state...

protected void onSaveInstanceState(Bundle outState)
{
    outState.putParcelable("outputFileUri", outputFileUri);
}

...

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    if (savedInstanceState != null)
    {
        outputFileUri= savedInstanceState.getParcelable("outputFileUri");
    }
}


回答2:

I think the issue has to do with your managing of the outputFileUri member var across the standard Android activity lifecycle.

When you call StartActivityForResult, your activity is getting stopped and probably destroyed. When capture intent returns, your activity gets re-created and resumed. You probably need to be persisting the value of outputFileUri across those lifecycle events.

See onCreate and onSaveInstanceState.

The only explination I have as to why the native app does this while whatever 3rd party camera app doesnt would be the somehow the native one consumes resources to the extent that your activity does actually get destroyed, wiping out your outputFileUri.

It might also be worth looking at the resultcode returned in onActivityResult to make sure camera intent says OK in addition to checking the uri/filepath to see that an image actually got captured. I bet it did.