Android意图 - 将uri传递给相机

时间:2014-06-18 23:29:23

标签: android android-intent

我正在尝试测试与通过相机拍摄图像相关的sample code。文档说如果相机将保存图像,则可以在意图中传递URI作为额外内容。

我尝试了以下内容:

// image1 doesn't exist
File file = new File(getFilesDir() + "/image1");
Uri uri = Uri.fromFile(file);

Intent i = new Intent();
i.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, uri);

if (i.resolveActivity(getPackageManager()) != null) {
     startActivityForResult(i, 1337);
}

我正在尝试将图像作为名为image1的文件放在我的files目录中。我在genymotion VM上测试它。我已经测试过将图像作为返回Intent中的位图,但是当我使用上述方法时,在拍摄照片后点击完成时相机应用程序会卡住。

我猜它与URI权限有关。我是否需要在数据共享中添加一些权限?

修改

我试图关注这些instructions,除了我想将照片保存在我的应用程序目录中,所以我尝试了以下但是它不起作用(该应用程序具有相机权限):

 String imagePath = null;
 try {
      File image = File.createTempFile("testImage", ".jpg", getFilesDir());
      imagePath = "file://" + image.getAbsolutePath();
 }
 catch(Exception e){
    Toast.makeText(getApplicationContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
 }

 File file = new File(imagePath);
 Uri uri = Uri.fromFile(file);


 Intent i = new Intent();
 i.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
 i.putExtra(MediaStore.EXTRA_OUTPUT, uri);

 if (i.resolveActivity(getPackageManager()) != null) {
    startActivityForResult(i, 1337);
 }

我也有onActivityResult(),但它没用,因为相机应用程序卡住了,如上所述。

另外,还有一个问题:当我在测试应用中没有相机权限时,我仍然可以调用相机并在意图中获取位图,怎么做?这是genymotion VM特有的吗?

1 个答案:

答案 0 :(得分:1)

确保您拥有清单的这些权限

 <uses-permission android:name="android.permission.CAMERA" />
 <uses-feature android:name="android.hardware.camera" />
 <uses-feature android:name="android.hardware.camera.autofocus" />

一切对我来说都很好。你有onActivityResult()

吗?
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == RESULT_OK){
            String result=data.getStringExtra("result");
        }
        if (resultCode == RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}//onActivityResult
相关问题