Android相机意图返回null ...有时候

时间:2014-05-11 12:40:09

标签: android android-intent camera

我正在两个不同的物理设备中调试我的应用程序:

  • Motorola Moto G,Android 4.4.2
  • LG OPTIMUS L5 II,Android 4.1.2

我正在按钮中调用相机:

buttonCamera.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
            }
        });

我像这样管理意图结果:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Uri selectedImage = data.getData(); // <-- Sometimes null
    }

这里的问题是摩托罗拉Moto G中data.getData()为空,而LG OPTIMUS中没有,为什么会这样?我怎样才能避免在摩托罗拉Moto G中获得null?

1 个答案:

答案 0 :(得分:3)

这个答案有点晚了,但我刚才遇到了同样的问题,我找到了一个解决方案:

private static final String STATE_FILE_URI = "state_file_uri";
private static final int BROWSE_CAMERA = 111;
private String fileUri;

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString(STATE_FILE_URI, fileUri);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        fileUri = savedInstanceState.getString(STATE_FILE_URI);
        super.onRestoreInstanceState(savedInstanceState);
    }

    private void takePictureIntent(){
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        fileUri = "your_uri";
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(fileUri)));
        startActivityForResult(takePictureIntent, BROWSE_CAMERA);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {          
            if (requestCode == BROWSE_CAMERA) {
                if (data == null) {
                    onDeliveryPicture(Uri.parse("file://" + fileUri));
                } else {
                    onDeliveryPicture(data.getData());
                }
            }
        }
    }

    private void onDeliveryPicture(Uri uri) {
        ...
    }

希望它有所帮助!