android camera:onActivityResult()如果有额外的,则intent为null

时间:2012-09-24 11:26:57

标签: android android-camera-intent

在Stack Overflow的所有相关问题中搜索了很多内容并找不到任何内容后,请尽量帮助我。

我创建了捕获图片的意图。然后我在onActivityResult()看到了不同的行为:如果我没有在Intent中添加任何额外的内容(对于小图片)onActivityResult中的Intent是可以的,但是当我在将pic写入文件的意图中添加额外内容时,onActivityResult的意图是null

意图创造:

Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// without the following line the intent is ok
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(takePictureIntent, actionCode);

为什么它为null,我该如何解决?

5 个答案:

答案 0 :(得分:59)

对我来说也是如此,如果你提供MediaStore.EXTRA_OUTPUT,那么意图为空,但你会在你提供的文件中有照片(Uri.fromFile(f))。

如果您未指定MediaStore.EXTRA_OUTPUT,那么您将拥有一个意图,其中包含相机保存照片的文件中的uri。

不知道它是否是一个bug,但它的工作原理。

编辑:因此在onActivityResult()中,如果为null,则不再需要检查数据。以下是我的工作:

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case PICK_IMAGE_REQUEST://actionCode
            if (resultCode == RESULT_OK && data != null && data.getData() != null) {
                //For Image Gallery
            }
            return;

        case CAPTURE_IMAGE_REQUEST://actionCode
            if (resultCode == RESULT_OK) {
                //For CAMERA
                //You can use image PATH that you already created its file by the intent that launched the CAMERA (MediaStore.EXTRA_OUTPUT)
                return;
            }
    }
}

希望有所帮助

答案 1 :(得分:1)

用Kotlin写的样本。您为相机应用创建UriCameraFragment保留相机,直到相机从保存图片返回并按照您的预期将其返回给onActivityResult

CameraFragment.kt

充当消费者和相机应用之间的媒介。将Uri作为输入并将其返回到数据Intent

class CameraFragment : Fragment() {

    companion object {
        val TAG = CameraFragment::class.java.simpleName

        private val KEY_URI = ".URI"

        fun newInstance(uri: Uri, targetFragment: Fragment, requestCode: Int): CameraFragment {
            val args = Bundle()
            args.putParcelable(KEY_URI, uri)
            val fragment = CameraFragment()
            fragment.arguments = args
            fragment.setTargetFragment(targetFragment, requestCode)
            return fragment
        }
    }

    private lateinit var uri: Uri

    private var fired = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        retainInstance = true

        fired = savedInstanceState?.getBoolean("fired") ?: false

        if (!fired) {
            val args = arguments
            uri = args.getParcelable(KEY_URI)

            val i = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            i.putExtra(MediaStore.EXTRA_OUTPUT, uri)
            i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            context.grantUriPermission(i, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)

            startActivityForResult(i, targetRequestCode)
            fired = true
        }
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        outState.putBoolean("fired", fired)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == targetRequestCode) {
            context.revokeUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION)

            val newData = Intent()
            newData.data = uri
            targetFragment.onActivityResult(requestCode, resultCode, newData)

            dismiss()
        }
    }

    private fun dismiss() {
        fragmentManager.beginTransaction().remove(this).commit()
    }
}

/** Grant Uri permissions for all camera apps. */
fun Context.grantUriPermission(intent: Intent, uri: Uri, modeFlags: Int) {
    val resolvedIntentActivities = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
    for (resolvedIntentInfo in resolvedIntentActivities) {
        val packageName = resolvedIntentInfo.activityInfo.packageName;
        grantUriPermission(packageName, uri, modeFlags);
    }
}

调用相机意图

this是您应用中的一个片段,会触发相机。 RC_CAMERA是此操作的请求代码。

val uri = /* Your output Uri. */
val f = CameraFragment.newInstance(uri, this, RC_CAMERA)
fragmentManager.beginTransaction().add(f, CameraFragment.TAG).commit()

处理相机结果

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    when(requestCode) {
        RC_CAMERA -> {
            if (resultCode == Activity.RESULT_OK) {
                val uri = data?.data
                // Do whatever you need.
            }
        }
    }
}

答案 2 :(得分:0)

您在哪里为f创建了Uri.fromFile(f)

它必须是有效的File对象。尝试在EXTRA_OUTPUT行之前创建它。

File f = new File("valid path");

尝试这样的事情:

File file = new File(dataFile);
Uri outFileUri = Uri.fromFile(file);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, outFileUri);
startActivityForResult(intent, TAKE_PHOTO);

答案 3 :(得分:0)

当我们从android的Camera中捕获图像时,Uridata.getdata()为空。我们有两种解决方案来解决此问题。

  1. 我们可以从位图图像中获取Uri路径
  2. 我们可以从光标处获取Uri路径。

我将在这里实现所有方法,请仔细阅读以下内容:-

首先,我将告诉您如何从位图图像获取Uri: 完整的代码是:

首先,我们将通过Intent捕获图像,这两种方法都相同,因此我只在这里编写这段代码:

 // Capture Image


  captureImg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivityForResult(intent, reqcode);
            }

        }
    });

现在,我们将实现OnActivityResult :-(这对于以上两种方法都是相同的):-

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


            if(requestCode==reqcode && resultCode==RESULT_OK)
            {

    Bitmap photo = (Bitmap) data.getExtras().get("data");
    ImageView.setImageBitmap(photo);

                // CALL THIS METHOD TO GET THE URI FROM THE BITMAP
                Uri tempUri = getImageUri(getApplicationContext(), photo);

                \\ Show Uri path based on Image
                Toast.makeText(LiveImage.this,"Here "+ tempUri, Toast.LENGTH_LONG).show();

               \\ Show Uri path based on Cursor Content Resolver
                Toast.makeText(this, "Real path for URI : "+getRealPathFromURI(tempUri), Toast.LENGTH_SHORT).show();
    }
            else
            {
                Toast.makeText(this, "Failed To Capture Image", Toast.LENGTH_SHORT).show();
            }
        }

\现在,我们将创建上述所有方法,以通过类通过Image和Cursor方法创建Uri:

现在位图图像的URI路径

 private Uri getImageUri(Context applicationContext, Bitmap photo) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        photo.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        String path = MediaStore.Images.Media.insertImage(LiveImage.this.getContentResolver(), photo, "Title", null);
        return Uri.parse(path);
    }

\ Uri来自已保存图像的真实路径

  public String getRealPathFromURI(Uri uri) {
        Cursor cursor = getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(idx);
    }

答案 4 :(得分:-6)

使用以下内容:

位图位图= data.getExtras()。getParcelable(“data”);

它有效。