android - 选择意图

时间:2016-11-05 00:00:46

标签: java android android-intent

此图显示了用于选择图像或用相机拍照的应用程序的框。如果我选择相机,这让我拍照,但没有返回或保存选项。我更新了发布活动结果代码的答案。

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        switch (requestCode)
        {
            case 1:
                if (data != null)
                {
                    Log.e("TAG", "Only called when a image from gallery is selected");
                }
                else
                {
                    Log.e("TAG", "Data is null");
                }
                break;

        }
    }
   private void ChooseImage()
{

    // Create gallery intent
    Intent _intentGallery = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    _intentGallery.setAction(Intent.ACTION_PICK);
    _intentGallery.putExtra("return-data", true);

   // startActivityForResult(_intentGallery, 1);


    // Create camera intent
    Intent galleryIntent = new  Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    // Create chooser
    Intent chooser = Intent.createChooser(galleryIntent, getString(R.string.choose_an_application));

    // Create list of gallery intents
    List<Intent> galleryIntents = new ArrayList<Intent>();

    // Add intents to list
    PackageManager pm = getApplicationContext().getPackageManager();
    for (ResolveInfo ri: pm.queryIntentActivities(_intentGallery, PackageManager.MATCH_DEFAULT_ONLY))
    {
        Intent intent = pm.getLaunchIntentForPackage(ri.activityInfo.packageName);
        intent.setAction(Intent.ACTION_PICK);
        intent.putExtra("return-data", true);
        galleryIntents.add(intent);
    }

    // Show dialog
    chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, galleryIntents.toArray(new Parcelable[] {}));
    startActivityForResult(chooser, 1);
}

清单权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />

1 个答案:

答案 0 :(得分:0)

您必须实施onActivityResult。然后你就可以得到数据了。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bundle extras = data.getExtras();
        Bitmap imageBitmap = (Bitmap) extras.get("data");
        mImageView.setImageBitmap(imageBitmap);
    }
}

在这种情况下,REQUEST_IMAGE_CAPTURE在您定义时为1,因此将其更改为1。 不要忘记清单规则uses-feature

查看更多:https://developer.android.com/training/camera/photobasics.html