简体   繁体   English

来自画廊的图像,照片和相机始终无法正常工作

[英]Image from gallery, photos and camera not working always

  final List<Intent> cameraIntents = new ArrayList<Intent>(); final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); final PackageManager packageManager = getPackageManager(); final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0); for (ResolveInfo res : listCam) { final String packageName = res.activityInfo.packageName; final Intent intent = new Intent(captureIntent); intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name)); intent.setPackage(packageName); cameraIntents.add(intent); } Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); galleryIntent.setAction(Intent.ACTION_GET_CONTENT); final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source"); chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{})); startActivityForResult(chooserIntent, 1); 

So , thats How I call to open either camera or take a picture. 因此,这就是我所谓的打开相机或拍照的方式。 How i read them on onactivityresult????check below the code. 我如何阅读onactivityresult上的内容? The problem, when image chosen from photos it works, when taken from camera it works. 问题是,当从照片中选择图像时,它起作用了;从相机中拍摄时,它起作用了。 But when chosen from gallery folder, it doesnt work for some reason. 但是,从Gallery文件夹中选择时,由于某种原因,它不起作用。 Also some of clients are reporting me problem on sony xperia e4 phones. 另外,有些客户向我报告索尼xperia e4手机存在问题。

 @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); try { if (resultCode == Activity.RESULT_OK && requestCode == 1 ) { Bitmap bm = null; try { Bundle extras = data.getExtras(); bm = (Bitmap) extras.get("data"); } catch(Exception e) { try { Uri selectedImage = data.getData(); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = false; options.inPreferredConfig = Bitmap.Config.RGB_565; options.inDither = true; String[] filePathColumn = {MediaStore.Images.Media.DATA}; Cursor cursor = getContentResolver().query( selectedImage, filePathColumn, null, null, null); cursor.moveToFirst(); int columnIndex = cursor.getColumnIndex(filePathColumn[0]); String filePath = cursor.getString(columnIndex); cursor.close(); Common.setBitmap(null); bm = BitmapFactory.decodeFile(filePath); BitmapFactory.decodeFile(Common.getRealPathFromURI(data.getData(), rootView.getContext()), bounds); if(bm == null) bm = BitmapFactory.decodeFile(Common.getRealPathFromURI(selectedImage, AddStoreActivity.this), options); if(bm == null) bm = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImage); } catch(Exception e1) { } } } } catch (Exception e) { } } public static String getRealPathFromURI(Uri contentURI, Context cont) { Cursor cursor = cont.getContentResolver().query(contentURI, null, null, null, null); if (cursor == null) { // Source is Dropbox or other similar local file path return contentURI.getPath(); } else { cursor.moveToFirst(); int idx = cursor.getColumnIndex(MediaColumns.DATA); return cursor.getString(idx); } } 

This is how I do this and it works: 这是我这样做的方法,并且有效:

private void displayAddPhotoDialog() {
        final CharSequence[] items = getResources().getStringArray(R.array.photo_dialog_options);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle(getResources().getString(R.string.photo_dialog_title));
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (item == TAKE_PHOTO_OPTION) {
                    dispatchTakePictureIntent();
                } else if (item == CHOOSE_FROM_LIBRARY_OPTION) {
                    dispatchPickImageIntent();
                } else if (item == CANCEL_OPTION) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }


protected void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
                imageUri = Uri.fromFile(photoFile);
            } catch (IOException ex) {
                Toast.makeText(getActivity(), ex.toString(), Toast.LENGTH_SHORT).show();
            }
            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
            }
        } else {
            Toast.makeText(getActivity(), R.string.no_camera_error_message, Toast.LENGTH_SHORT).show();
        }
    }


    protected void dispatchPickImageIntent() {
        Intent intent = new Intent();
        intent.setType("image/*");
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            intent.setAction(Intent.ACTION_GET_CONTENT);
        } else {
            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        }
        startActivityForResult(Intent.createChooser(intent, getString(R.string.select_picture)), GALLERY_REQUEST_CODE);
    }

And your onActivityResult method should look like this: 并且您的onActivityResult方法应如下所示:

@Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            photoReceivedFromCamera = true;
            getActivity().getContentResolver().notifyChange(imageUri, null);
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            mediaScanIntent.setData(imageUri);
            getActivity().sendBroadcast(mediaScanIntent);
            //do want you want with the uri(taken photo)
        } else if (requestCode == CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_CANCELED) {
            //The user cancelled the take picture action...
            if (!photoReceivedFromCamera) {
                //If the user has not previously taken a picture,
                //this means he is cancelling the take photo process
                onCancelTakePicture();
            }
        } else if (requestCode == GALLERY_REQUEST_CODE && data != null && data.getData() != null) {
            Uri uri = data.getData();
           //do want you want with the uri(selected image)
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM