问题
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 itIf not, and
getData()
on theIntent
given to you inonActivityResult()
returns aUri
(and notnull
), use that (and if you truly need aFile
, useContentResolver
andopenInputStream()
with theUri
and copy the contents into your own file)If neither are true, and
getParcelableExtra("data")
returns a value, save thatBitmap
to a fileIf 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