I have a great problem to resolve on my app.
I'm try pick a custom file or content using the code below
public void openFolderToFile(Fragment fragment, String filter) {
int PICKFILE_RESULT_CODE = 1; //101;
int READ_REQUEST_CODE = 42;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
// intent.setAction(Intent.ACTION_GET_CONTENT);
if (intent.hasCategory(Intent.CATEGORY_OPENABLE)) {
intent.removeCategory(Intent.CATEGORY_OPENABLE);
}
if (!intent.hasCategory(Intent.CATEGORY_DEFAULT)) {
intent.addCategory(Intent.CATEGORY_DEFAULT);
}
intent.setFlags(intent.getFlags()
| Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
| Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_PREFIX_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
// intent.addCategory(Intent.ACTION_OPEN_DOCUMENT);
// intent.addCategory(Intent.CATEGORY_OPENABLE);
// intent.addCategory(Intent.CATEGORY_DEFAULT);
// intent.addCategory(Intent.CATEGORY_BROWSABLE);
// intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
// intent.createChooser(target, title)
filter = filter == null ? "file/*" : filter;
intent.setType(filter);
// Uri uri =
// Uri.parse(Environment.getDownloadCacheDirectory().getPath());
// intent.setDataAndType(uri, "text/nhpz,text/nhpz2");
intent.putExtra("CONTENT_TYPE", filter);
fragment.startActivityForResult(intent, PICKFILE_RESULT_CODE);
/*
* fragment.startActivityForResult( intent.createChooser(intent,
* "Select your file"), PICKFILE_RESULT_CODE);
*/
}
And this method can be used of this way...
String filter = "text/nhpz,text/nhpz2";
openFolderToFile(myFragment, filter);
or
String filter = "*/nhpz,*/nhpz2";
openFolderToFile(myFragment, filter);
The String filter could be any others custons extensions.
This code work fine, but in some devices when I try pick my custom file directly of download folder without using external apps my file cannot be selected.
I'm try any others combinations of similar codes, when you can see commented and the result is the same.
I can selected my file or content using externals apps during the process, but if I try selected directly of my sdcard or download folder I can't, and I need make this on my application, because I can not force the user to install an external application to use with my app.
Does someone have any idea to help me?
Related
I am working on an application in which a user selects a pdf file and then it gets uploaded on firebase. The problem is when a user wants to select a file then other files which are not pdf are also shown. I want to restrict it and want to show pdf files only.
I am using this code to select pdf files only but its showing other files as well.
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
startActivityForResult(intent.createChooser(intent, "Select PDF file"), FILE_CHOOSER);
How can i do it? Any help?
I am using this code to open PDF files only.
String[] supportedMimeTypes = {"application/pdf"};
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent.setType(supportedMimeTypes.length == 1 ? supportedMimeTypes[0] : "*/*");
if (supportedMimeTypes.length > 0) {
intent.putExtra(Intent.EXTRA_MIME_TYPES, supportedMimeTypes);
}
} else {
String mimeTypes = "";
for (String mimeType : supportedMimeTypes) {
mimeTypes += mimeType + "|";
}
intent.setType(mimeTypes.substring(0,mimeTypes.length() - 1));
}
startActivityForResult(intent, FILE_CHOOSER);
I am trying to pick Audio from Gallery. I am using the following intent.
private void selectAudioFromGallery() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("audio/3gp, audio/AMR, audio/mp3");
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_audio_file_title)), REQ_CODE_PICK_SOUNDFILE);
}
I want to select files of type 3gp, AMR, mp3 and only these files should be listed in the file chooser but the problem I am facing it, it also shows the other files too like text files, image etc.
Intent intent = null;
if(Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
intent = new Intent(Intent.ACTION_GET_CONTENT);
}else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
}
// The MIME data type filter
intent.setType("audio/*")
Works..
Use this
intent.setType("audio/3gp|audio/AMR|audio/mp3");
Adding multiple mime type need pipe sign, not comma.
Another way
intent.setType("audio/*");
String[] mimetypes = {"audio/3gp", "audio/AMR", "audio/mp3"};
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
I thought this would be easy but as it turns out unfortunately it's not.
What I have:
I have a folder called "myFolder" on my external storage (not sd card because it's a Nexus 4, but that should not be the problem). The folder contains some *.csv files.
What I want:
I want to write a method which does the following: Show a variety of apps (file browsers) from which I can pick one (see picture). After I click on it, the selected file browser should start and show me the content of "myFolder". No more no less.
My question:
How exactly do I do that? I think I came quite close with the following code, but no matter what I do - and I'm certain that there must be something I didn't get right yet - it always opens only the main folder from the external storage.
public void openFolder()
{
File file = new File(Environment.getExternalStorageDirectory(),
"myFolder");
Log.d("path", file.toString());
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setDataAndType(Uri.fromFile(file), "*/*");
startActivity(intent);
}
This should help you:
Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() + "/myFolder/");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, "resource/folder");
if (intent.resolveActivityInfo(getPackageManager(), 0) != null)
{
startActivity(intent);
}
else
{
// if you reach this place, it means there is no any file
// explorer app installed on your device
}
Please, be sure that you have any file explorer app installed on your device.
EDIT: added a shantanu's recommendation from the comment.
LIBRARIES:
You can also have a look at the following libraries https://android-arsenal.com/tag/35 if the current solution doesn't help you.
I finally got it working. This way only a few apps are shown by the chooser (Google Drive, Dropbox, Root Explorer, and Solid Explorer). It's working fine with the two explorers but not with Google Drive and Dropbox (I guess because they cannot access the external storage). The other MIME type like "*/*" is also possible.
public void openFolder(){
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getExternalStorageDirectory().getPath()
+ File.separator + "myFolder" + File.separator);
intent.setDataAndType(uri, "text/csv");
startActivity(Intent.createChooser(intent, "Open folder"));
}
Here is my answer
private fun openFolder() {
val location = "/storage/emulated/0/Download/";
val intent = Intent(Intent.ACTION_VIEW)
val myDir: Uri = FileProvider.getUriForFile(context, context.applicationContext.packageName + ".provider", File(location))
intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
intent.setDataAndType(myDir, DocumentsContract.Document.MIME_TYPE_DIR)
else intent.setDataAndType(myDir, "*/*")
if (intent.resolveActivityInfo(context.packageManager, 0) != null)
{
context.startActivity(intent)
}
else
{
// if you reach this place, it means there is no any file
// explorer app installed on your device
CustomToast.toastIt(context,context.getString(R.string.there_is_no_file_explorer_app_present_text))
}
}
Here why I used FileProvider - android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()
I tested on this device
Devices: Samsung SM-G950F (dreamltexx), Os API Level: 28
Intent chooser = new Intent(Intent.ACTION_GET_CONTENT);
Uri uri = Uri.parse(Environment.getDownloadCacheDirectory().getPath().toString());
chooser.addCategory(Intent.CATEGORY_OPENABLE);
chooser.setDataAndType(uri, "*/*");
// startActivity(chooser);
try {
startActivityForResult(chooser, SELECT_FILE);
}
catch (android.content.ActivityNotFoundException ex)
{
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
In code above, if setDataAndType is "*/*" a builtin file browser is opened to pick any file, if I set "text/plain" Dropbox is opened. I have Dropbox, Google Drive installed. If I uninstall Dropbox only "*/*" works to open file browser. This is Android 4.4.2. I can download contents from Dropbox and for Google Drive, by getContentResolver().openInputStream(data.getData()).
Thread is old but I needed this kind of feature in my application and I found a way to do it so I decided to post it if it can help anyone in my situation.
As our device fleet is composed only by Samsung Galaxy Tab 2, I just had to find the file explorer's package name, give the right path and I succeed open my file explorer where I wanted to. I wish I could use Intent.CATEGORY_APP_FILES but it is only available in API 29.
Intent intent = context.getPackageManager().getLaunchIntentForPackage("com.sec.android.app.myfiles");
Uri uri = Uri.parse(rootPath);
if (intent != null) {
intent.setData(uri);
startActivity(intent);
}
As I said, it was easy for me because our clients have the same device but it may help others to find a workaround for their own situation.
this code will work with OI File Manager :
File root = new File(Environment.getExternalStorageDirectory().getPath()
+ "/myFolder/");
Uri uri = Uri.fromFile(root);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setData(uri);
startActivityForResult(intent, 1);
you can get OI File manager here : http://www.openintents.org/en/filemanager
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, DocumentsContract.Document.MIME_TYPE_DIR);
startActivity(intent);
Will open files app home screen
Today, you should be representing a folder using its content: URI as obtained from the Storage Access Framework, and opening it should be as simple as:
Intent i = new Intent(Intent.ACTION_VIEW, uri);
startActivity(i);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("text/csv");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), 0);
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
}
then you just need to add the response
public void onActivityResult(int requestCode, int resultCode, Intent data){
switch (requestCode) {
case 0: {
//what you want to do
//file = new File(uri.getPath());
}
}
}
You seem close.
I would try to set the URI like this :
String folderPath = Environment.getExternalStorageDirectory()+"/pathTo/folder";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
Uri myUri = Uri.parse(folderPath);
intent.setDataAndType(myUri , "file/*");
startActivity(intent);
But it's not so different from what you have tried.
Tell us if it changes anything ?
Also make sure the targeted folder exists, and have a look on the resulting Uri object before to send it to the intent, it may not be what we are expected.
File temp = File.createTempFile("preview", ".png" );
String fullfileName= temp.getAbsolutePath();
final String fileName = Uri.parse(fullfileName)
.getLastPathSegment();
final String filePath = fullfileName.
substring(0,fullfileName.lastIndexOf(File.separator));
Log.d("filePath", "filePath: " + filePath);
fullfileName:
/mnt/sdcard/Download_Manager_Farsi/preview.png
filePath:
/mnt/sdcard/Download_Manager_Farsi
How to use intent to prompt user to choose "finish action with" to choosing app to select file (assuming there is a few app to browse file in the device)
I want to filter the file using an extension.. (eg. : *.sav, *.props)
Thank you in advance
You can use something like this:
....
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, YOUR_RESULT_CODE);
....
But I really doubt that you can set a filter third-party file browsers.
Or you can try to use this file dialog: http://code.google.com/p/android-file-dialog/
this will open the build-in file explorer if available, otherwise will ask u to select a file explorer that u have installed.
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//intent.setType("*/*"); //all files
intent.setType("text/xml"); //XML file only
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent, "Select a File to Upload"), FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.", Toast.LENGTH_SHORT).show();
}
}
It may help you to choose a doc file and u may change action as per your need
Intent intent;
if (VERSION.SDK_INT >= 19) {
intent = new Intent("android.intent.action.OPEN_DOCUMENT");
intent.setType("*/*");
} else {
PackageManager packageManager =getActivity().getPackageManager();
intent = new Intent("android.intent.action.GET_CONTENT");
intent.setType("file*//*");
if (packageManager.queryIntentActivities(intent,MEDIA_TYPE_IMAGE).size() == 0) {
UserToast.show(getActivity(), getResources().getString(R.string.no_file_manager_present));
}
}
if (getActivity().getPackageManager().resolveActivity(intent, NativeProtocol.MESSAGE_GET_ACCESS_TOKEN_REQUEST) != null) {
startActivityForResult(intent, UPLOAD_FILE);
}
// check here to KitKat or new version and this will solve the Samsung file explore issue too.
boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat) {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,FILE_SELECT_CODE);
} else {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent,FILE_SELECT_CODE);
}
I would like to start an intentchooser for apps which can return any kind of file
Currently I use (which I copied from the Android email source code for file attachment)
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
Intent i = Intent.createChooser(intent, "File");
startActivityForResult(i, CHOOSE_FILE_REQUESTCODE);
But it only shows "Gallery" and "Music player" on my Galaxy S2. There is a file explorer on this device and I would like it to appear in the list. I would also like the camera app to show in the list, so that the user can shoot a picture and send it through my app.
If I install Astro file manager it will respond to that intent, too. My customers are Galaxy SII owners only and I don't want to force them to install Astro file manager given that they already have a basic but sufficient file manager.
Any idea of how I could achieve this ? I am pretty sure that I already saw the default file manager appear in such a menu to pick a file, but I can't remember in which app.
Not for camera but for other files..
In my device I have ES File Explorer installed and This simply thing works in my case..
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("file/*");
startActivityForResult(intent, PICKFILE_REQUEST_CODE);
Samsung file explorer needs not only custom action (com.sec.android.app.myfiles.PICK_DATA),
but also category part (Intent.CATEGORY_DEFAULT) and mime-type should be passed as extra.
Intent intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);
You can also use this action for opening multiple files: com.sec.android.app.myfiles.PICK_DATA_MULTIPLE
Anyway here is my solution which works on Samsung and other devices:
public void openFile(String mimeType) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(mimeType);
intent.addCategory(Intent.CATEGORY_OPENABLE);
// special intent for Samsung file manager
Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
// if you want any file type, you can skip next line
sIntent.putExtra("CONTENT_TYPE", mimeType);
sIntent.addCategory(Intent.CATEGORY_DEFAULT);
Intent chooserIntent;
if (getPackageManager().resolveActivity(sIntent, 0) != null){
// it is device with Samsung file manager
chooserIntent = Intent.createChooser(sIntent, "Open file");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { intent});
} else {
chooserIntent = Intent.createChooser(intent, "Open file");
}
try {
startActivityForResult(chooserIntent, CHOOSE_FILE_REQUESTCODE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getApplicationContext(), "No suitable File Manager was found.", Toast.LENGTH_SHORT).show();
}
}
This solution works well for me, and maybe will be useful for someone else.
this work for me on galaxy note
its show
contacts,
file managers installed on device,
gallery,
music player
private void openFile(Int CODE) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("*/*");
startActivityForResult(intent, CODE);
}
here get path in onActivityResult of activity.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String Fpath = data.getDataString();
// do somthing...
super.onActivityResult(requestCode, resultCode, data);
}
This gives me the best result:
Intent intent;
if (android.os.Build.MANUFACTURER.equalsIgnoreCase("samsung")) {
intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);
} else {
String[] mimeTypes =
{"application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
"application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
"application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
"text/plain",
"application/pdf",
"application/zip", "application/vnd.android.package-archive"};
intent = new Intent(Intent.ACTION_GET_CONTENT); // or ACTION_OPEN_DOCUMENT
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
}
Turns out the Samsung file explorer uses a custom action. This is why I could see the Samsung file explorer when looking for a file from the samsung apps, but not from mine.
The action is "com.sec.android.app.myfiles.PICK_DATA"
I created a custom Activity Picker which displays activities filtering both intents.
If you want to know this, it exists an open source library called aFileDialog that it is an small and easy to use which provides a file picker.
The difference with another file chooser's libraries for Android is that aFileDialog gives you the option to open the file chooser as a Dialog and as an Activity.
It also lets you to select folders, create files, filter files using regular expressions and show confirmation dialogs.
The other answers are not incorrect. However, now there are more options for opening files. For example, if you want the app to have long term, permanent acess to a file, you can use ACTION_OPEN_DOCUMENT instead. Refer to the official documentation: Open files using storage access framework. Also refer to this answer.