Set default image gallery on kotlin - android

I am trying to implement gallery functionality in kotlin with android studio using default component. The goal is to click a button and open the desired path as a common Intent .
I can't understand how it is possible that the emulator only opens recent images for me instead of the path I specified on the file provider.
enter image description here
The part of code that I'm using is :
fun dispatcherGalleryImage(){
try {
val uri: Uri = Uri.parse(Environment.getExternalStoragePublicDirectory(requireActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES).toString().replace("/storage/emulated/0", "")).path.toString())
Log.info(uri.toString())
val intent=Intent(Intent.ACTION_GET_CONTENT)
intent.type ="image/*"
startActivityForResult(intent, TAKE_GALLERY_IMAGE)
}catch (ex: Exception){
Log.info(ex.toString())
}
}

I can't understand how it is possible that the emulator only opens recent images for me instead of the path I specified on the file provider
First, you are not using uri, except to log its value.
Second, the string that you are passing to Uri.parse() is not a valid string representation of a Uri (use Uri.fromFile() for a File).
Third, you are not using FileProvider. And a file:/// Uri is largely useless on Android 7.0+, as it will trigger a FileUriExposedException if you pass it in an Intent.
Fourth, ACTION_GET_CONTENT does not take a Uri as input. It is unclear why you are using ACTION_GET_CONTENT when you already have the content.
If your objective is to let the user view the image in their desired image viewer, use ACTION_VIEW, and put the FileProvider-supplied Uri and concrete (non-wildcard) MIME type in the Intent.

Related

Can't figure out how to use ACTION_VIEW and Storage Access Framework together

After about a week of pulling my hair out, I'm finally done and ready to ask for some help.
Basically in my app I use the Intent below to create a new PDF, which is done via Storage Access Framework.
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "application/pdf"
intent.putExtra(Intent.EXTRA_TITLE, title)
startActivityForResult(intent, 1234)
After that I get the Uri on the onActivityResult() method, like so:
uri = dataIntent.data
if (uri != null) {
val takeFlags = data.flags and (Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
contentResolver.takePersistableUriPermission(uri, takeFlags)
generatePdf(uri)
}
PDF generation is ok, the problem comes when I need to call ACTION_VIEW for the user to see the generated file or to share the file using ACTION_SEND.
Example of ACTION_VIEW usage (Yes, I'm using both Kotlin and Java):
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(uri, mimeType);
startActivity(intent);
I can't for the life of me figure out how to get an Uri that another app can use.
What I tried so far:
This answer, but the following exception is thrown: java.lang.IllegalArgumentException: column '_data' does not exist. Available columns: [_display_name, _size]
DocumentFile, using DocumentFile.fromFile(file), which turns the Uri from content://com.myapp.provider/root/document/primary:folder-created-by-the-user/generated-pdf.pdf to file:///root/document/primary:folder-created-by-the-user/generated-pdf.pdf, and still no app can open it
Many many other things that I can't even remember anymore
If someone could shed some light on this issue would be truly appreciated.
In principle use the same uri as obtained at creating the file. But ...you cannot grant a read uri permission on that uri. You got it. But you cannot forward such a permission to a viewer of your document.
Instead you should implement a ContentProvider. Then you can serve the content of your file.
Like blackapps said in his response, what I had to do was implement a ContentProvider, more specifically a DocumentProvider.
Following this link and this link is what finally did the trick. I implemented a CustomDocumentProvider that exposes a folder inside my app's private files (context.getFilesDir().getAbsolutePath() + "/folderToExpose"), after that all files created in this folder were exposed to other apps and I could use ACTION_VIEW and ACTION_SEND normally.
If someone happens to come across this issue, just make sure that the folder you want to expose doesn't contain any files that are crucial to your app, like database files, since users will have full access to all of its contents. And if it is a new folder, make sure to create it by calling mkdirs().

is the Uri returned by Intent.ACTION_GET_CONTENT always somewhere on disk, or can it be anywhere?

Currently I have the following code that allows a user to choose an image.
int requestCode = 1337;
Intent chooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
chooserIntent.setType("image/*");
chooserIntent = Intent.createChooser(chooserIntent, "Please choose a picture");
chooserIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(chooserIntent, requestCode);
My question is:
does Android guarantee that the returned Uri is always pointing to a location on disk, or is it possible that it might be pointing to somewhere on the internet too?
P.S. although I am not sure about this, the Uri returned by this piece of code seems to always start with content:// - I am not sure whether or not this holds for all possible return values, I thought I would just add this here to help out any possible question answerers.
does Android guarantee that the returned Uri is always pointing to a
location on disk, or is it possible that it might be pointing to
somewhere on the internet too?
It is possible to have Uri other than local disk i.e. it can be remotely as well. You will get URL from remote then convert it to Uri and use it.
From official docs:
An ACTION_GET_CONTENT could allow the user to create the data as it
runs (for example taking a picture or recording a sound), let them
browse over the web and download the desired data, etc.
Convert Url to a Uri (Reference):
Uri uri = Uri.parse( "http://www.facebook.com" );

How to inspect ContentProvider available for Intent (or block specific one)

I use the Intent mechanism to have the user select an image via the standard way
val intent = Intent(Intent.ACTION_GET_CONTENT)
intent.type = "image/*"
intent.addCategory(Intent.CATEGORY_OPENABLE)
ctx.startActivityForResult(intent, RequestCodes.SelectPhoto)
then I pass the Uri to another activity to maybe crop the photo. I need the Uri before to do some pre-checks.
On the Android emulators, the default providers such as Photos (apparently) give my whole app permission to open the Uri, not just the requesting activity. However, there is a "weird" provider in Asia, com.miui.gallery.provider.GalleryOpenProvider that doesn't -- an evil SecurityException happens in the cropper.
So I try to use ACTION_OPEN_DOCUMENT, which per the specs say that it will give my whole app permission until device reboot, but unfortunately that one doesn't support Google Photos in the cloud, in the emulator.
So I am looking for a way to determine if com.miui.gallery.provider.GalleryOpenProvider is going to be on the list for GET_CONTENT, and if so either prevent it, or otherwise fall back to using ACTION_OPEN_DOCUMENT. I'd like to avoid copying the stream before giving the Uri to the cropper, the crop activity treats it as readonly anyway.
This the full function to start the crop (kotlin). CropActivity is a modification of the old open-source Gallery app com.android.gallery3d.
private fun startCrop(ctx: Activity, uri: Uri) {
val intent = Intent(ctx, CropActivity::class.java)
intent.data = uri
val file = this.createImageFile(ctx, "photofinal")
if (file == null) {
this.showStorageUnavailable(ctx)
return
}
val outputUri = Uri.fromFile(file)
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri)
intent.putExtra(CropExtras.KEY_MIN_CROP_SIDE, Config.minimumImageDimension)
intent.putExtra(CropExtras.KEY_MOST_OBLONG_ASPECT, Config.maxPhotoAspectRatio)
intent.putExtra(CropExtras.KEY_EXIF_ORIENTATION, exifOrientation)
ctx.startActivityForResult(intent, RequestCodes.CropPhoto)
}
then I pass the Uri to another activity to maybe crop the photo
Pass that Uri in the "data" facet of the Intent, and add FLAG_GRANT_READ_URI_PERMISSION to transfer read access to the other component. See this sample app:
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
if (resultCode==Activity.RESULT_OK) {
getActivity()
.startService(new Intent(getActivity(), DurablizerService.class)
.setData(resultData.getData())
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION));
}
}
Here, I happen to be passing the Uri to a service, but the same principle holds for an activity.
See also this blog post for more about Uri access lifetimes.
Or, don't use separate activities, but do something else (e.g., multiple fragments).
On the Android emulators, the default providers such as Photos (apparently) give my whole app permission to open the Uri, not just the requesting activity.
That would occur if the Uri has a file scheme or is from an exported permission-less ContentProvider.
So I try to use ACTION_OPEN_DOCUMENT, which per the specs say that it will give my whole app permission until device reboot
It is subject to the same general rules as the Uri values you get from ACTION_GET_CONTENT.
So I am looking for a way to determine if com.miui.gallery.provider.GalleryOpenProvider is going to be on the list for GET_CONTENT
That's not strictly possible. Any app could return a Uri from that provider. In practice, that provider may only be used by its hosting app. If you found the package name for that provider's app, and you used queryIntentActivities() on PackageManager with your ACTION_GET_CONTENT Intent, you could determine if an activity from that app is in the list of ACTION_GET_CONTENT implementations.
However, if you use FLAG_GRANT_READ_URI_PERMISSION, as I note earlier, that should not be necessary.
if so either prevent it
Other than by rolling your own "chooser"-style UI, that's not strictly possible.

android implicit intent edit failed to load image

This is my implicit intent to invoke image editing apps on the device:
startActivity(new Intent(Intent.ACTION_EDIT).setDataAndType(myUri,
getMimeType(myUri)).setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION |
Intent.FLAG_GRANT_WRITE_URI_PERMISSION));
And this is how I getMimeType:
public String getMimeType(Uri uri) {
String mimeType = null;
if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
ContentResolver cr = getContentResolver();
mimeType = cr.getType(uri);
} else {
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
.toString());
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
fileExtension.toLowerCase());
}
return mimeType;
}
For some apps it crashes to load:
On the app Sketch_Camera only an invisible page loads up and disables interaction with my app.
On the app AirBrush it loads the app but crashes with this message "Failed to load image".
Is it related to minimum sdk version as mine is 16?
I've tested this on minimum sdk version of 9 too and no change in result.
Is there anything else that I should add to this intent to work with all the apps?
I've tried putExtra too and it doesn't help:
.putExtra(Intent.ACTION_EDIT, myUri);
I've some gallery apps on my device and all of them launch Sketch_Camera and AirBrush without any problem.
What's happening here? I'm so confused after two days of struggling with this phenomena.
It's a file created from path of one media store file by querying MediaStore.Images.Media.EXTERNAL_CONTENT_URI
There is no guarantee that the other app has rights to this location, or even that your app has rights to this location. For example, the image could be on removable storage. Besides, the file Uri scheme is being banned for cross-app usage, anyway.
Use a content Uri instead. For example, in this sample app, I query MediaStore for videos. Given a Cursor named row positioned at a particular video, I generate the Uri for it via:
videoUri=
ContentUris.withAppendedId(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI, row.getInt(row.getColumnIndex(MediaStore.Video.Media._ID)));
This Uri both works for my own purposes (e.g., hand to Picasso to get a thumbnail, hand to VideoView for playback) and for handing to third-party apps (e.g., ACTION_VIEW for playback).
Other than changing the base Uri to the one you queried against (MediaStore.Images.Media.EXTERNAL_CONTENT_URI), the same basic code should work for you.
Also, get rid of the flags from your Intent. Those are only for where the Intent points to your own ContentProvider, which is not the case in either your original code or with the Uri that you create from withAppendedId().

Intent with ACTION_VIEW and uri pointing to a ParcelFileDescriptor in EXTRA_STREAM

what is the correct way how I should form the intent to show content from my app in 3rd party viewers? I need to show images in gallery (or any other image viewer), pdfs in some pdf reader,..
Data gets server through a content provider which implements the openFile() method and returns a output pipe..
ParcelFileDescriptor[] pipe=ParcelFileDescriptor.createPipe();
...
ParcelFileDescriptor.AutoCloseOutputStream stream = new ParcelFileDescriptor.AutoCloseOutputStream(pipe[1]);
PipeThread pipeThread = new PipeThread(fileContents, stream);
pipeThread.start();
return pipe[0];
For images I use this:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, uri);
I'm creating then a chooser for this intent as usual that's not the issue..
My problem is that although I see for example the Photos app in the chooser, I just cannot open the file in it..It just only opens the gallery with my images.
It's working when I use the action send, apps like gmail, drive, dropbox,..all of them are able to correctly read the image from the provider.
Also Skitch seems to be the only one app which I have tested it on that is able to open the image also using the Intent.ACTION_VIEW action..
Please don't tell me I should just send the URI, I really need to provide the file as a stream, or somehow as a serie of bytes (IPC limitations would be probably against this). I can't save the file to a public directory.
So the issue was that have been setting Intent type and data in two separate method calls..
What I didn't know is that Intent.setType() clears its data and Intent.setData() clears its type..
When I set both data and type through the Intent.setDataAndType() method call, it works even for URI pointing to a stream.
Unfortunately the final implementation is still not working flawlessly everywhere.
It works in default android gallery app, in G+ Photos app, in QuickPic, in Sony gallery app, but it does not work in default HTC gallery neither in default Samsung gallery.
Its just a pity, that its actually not that much dependent on my implementation as on how is it implemented in the 3rd party viewer app.

Categories

Resources