Proper solution to pick/click an image on Android

半世苍凉 提交于 2019-12-24 06:45:59

问题


As the title suggests, i'm having an option to upload an image in my app. I would like to have two options: Click a new picture & Select from gallery. Gallery selection is working fine on all devices using this code:

Intent in = new Intent();
in.setType("image/*");
in.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(in, getString(R.string.selectpicture)), 100);

The problem is with Click a new picture.

I want to use other camera apps installed on the device to get the image. This code should save the image user clicks at the specified path.

Intent m_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageUri = getImageUri();
m_intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(m_intent, REQUEST_IMAGE_CAPTURE);

But what happens is, the EXTRA_OUTPUT is not respected by all camera apps.

Also if memory is low, my app is killed by the system which makes things more complicated.

So, what's the best way to enable user to click a new picture and get the image path in my app? If using third party libraries is better, which one's are reliable?


回答1:


the EXTRA_OUTPUT is not respected by all camera apps.

Any time you delegate anything to a third party app, you can run into problems.

Also if memory is low, my app is killed by the system which makes things more complicated.

You need to handle this anyway. Save the value you put in EXTRA_OUTPUT in the saved instance state Bundle.

what's the best way to enable user to click a new picture and get the image path in my app?

If you wish to stick with ACTION_IMAGE_CAPTURE, I'd go with this triage:

  • If there is an image in the location you provided to EXTRA_OUTPUT, use it

  • If not, and getData() on the Intent given to you in onActivityResult() returns a Uri (and not null), use that (and if you truly need a File, use ContentResolver and openInputStream() with the Uri and copy the contents into your own file)

  • If neither are true, and getParcelableExtra("data") returns a value, save that Bitmap to a file

  • If none of those are true, suggest to the user to get a different camera app, perhaps pointing them to one that you have tried and know works

Or, take the picture yourself, directly or using a library like mine.



来源:https://stackoverflow.com/questions/41945165/proper-solution-to-pick-click-an-image-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!