Hi I want to browse to a file explorer and select a pdf or image present in some directory.
I want the code to do the same.
the below code takes me to gallery and help me choose image but I want to move to file explorer then select file and accordingly I want the code in onactivityResult after selecting.
browsePic.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI
);
startActivityForResult(i, LOAD_IMAGE_RESULTS);
}
});
I believe you can throw out an open intent for a file chooser using the following.
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("*/*");
try{
startActivityForResult(intent, LOAD_IMAGE_RESULTS);
} catch (ActivityNotFoundException e){
Toast.makeText(YourActivity.this, "There are no file explorer clients installed.", Toast.LENGTH_SHORT).show();
}
The trouble is however, this assumes your user has a file browser open to accepting intents installed on their device, when often no such apps are installed on a device by default.
As in the code above, you may have to throw up a dialog if no Activities exist that can accept this intent, explaining that they need to install a file browser. You could even recommend one that you know works with your application.
I hope this helps.
i think you could do something like this
File strDir = new File("/mnt/"); // where your folder you want to browse inside android
if( strDir.isDirectory()){
//do something
}
Related
I am trying to open a directory with the help of an intent to show the user what is the content inside that folder but I am unable to do so,
but I don't know why the folder won't open and I get this "Can't use this folder" on the file manager.
open.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + "/" + "XYZ";
Uri uri = Uri.parse(path);
Toast.makeText(MainActivity.this, ""+path, Toast.LENGTH_SHORT).show();
openDirectory(uri);
}
});
The method
public void openDirectory(Uri uriToLoad){
// Choose a directory using the system's file picker.
int result = 1;
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
// Optionally, specify a URI for the directory that should be opened in
// the system file picker when it loads.
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, uriToLoad);
startActivityForResult(intent, result);
}
I want to open the folder XYZ after clicking on the button
I am trying to open a directory with the help of an intent to show the user what is the content inside that folder
There is no standard Intent action for that, sorry. Your code is trying to let the user select a document tree.
It is also doing that incorrectly, as EXTRA_INITIAL_URI does not take a file:// Uri as a value. That needs to be some Uri that you obtained previously from the Storage Access Framework, such as via some past ACTION_OPEN_DOCUMENT_TREE request.
I don't know why the folder won't open and I get this "Can't use this folder" on the file manager
From Android's standpoint, your EXTRA_INITIAL_URI value is little better than a random string.
But the user won't know where actually XYZ folder is
Then perhaps you should have let the user choose the location in the first place, rather than forcing a particular location. For example, you could use ACTION_CREATE_DOCUMENT to let the user decide where to place the document on the user's device (or the user's cloud storage, the user's network file server, etc.).
As far as I know using Intent you can browse, open and create files, that shared for all apps by the system. In this case for get file path to open, you can use next code like this (pardon for my Kotlin):
private var launcherForResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result.resultCode == Activity.RESULT_OK) {
result.data.also { uri -> filePath = uri.toString() }
}
}
private fun getFilePath() {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
type = "*/*"
addCategory(Intent.CATEGORY_OPENABLE)
}
launcherForResult.launch(intent)
}
As for the directory, it usually opens the last one that was opened before.
If you don't want other applications to see your files, store them in your application's private directory
I'm developing an app that saves data into a database, I'm trying to backup and restore that database which I am able to do, my issue is with the "ominous" permmission popup on API30+
Allow management of all files
Allow this app to access modify and delete files on your device.....
Allow this app to access, modify and delete files on the device or any connected storage devices? this app may access files without asking you.
I'm not trying to do any of these things, I just want permission to do the backup/restore thing
here's my code for requesting permission:
private void requestStoragePermissionExport(){
if( (Build.VERSION.SDK_INT >= 30 )){
try {
Intent intent = new Intent(Manifest.permission.MANAGE_EXTERNAL_STORAGE);
intent.addCategory("android.intent.category.DEFAULT");
intent.setData(Uri.parse(String.format("package:%s",getApplicationContext().getPackageName())));
startActivityForResult(intent, 2296);
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivityForResult(intent, 2296);
}
}else{
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE}, BACKUP_CODE);
}
}
is there a better way to handle this?
Google is restricting use of broad file permissions such as MANAGE_EXTERNAL_STORAGE. You can use Storage Access Framework to gain limited access to certain files or directories.
// Request code for selecting a PDF document.
const val PICK_PDF_FILE = 2
fun openFile(pickerInitialUri: Uri) {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "application/pdf"
// Optionally, specify a URI for the file that should appear in the
// system file picker when it loads.
putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri)
}
startActivityForResult(intent, PICK_PDF_FILE)
}
Or if you want to access an entire directory;
fun openDirectory(pickerInitialUri: Uri) {
// Choose a directory using the system's file picker.
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
// Optionally, specify a URI for the directory that should be opened in
// the system file picker when it loads.
putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri)
}
startActivityForResult(intent, your-request-code)
}
There are some restrictions to which paths you can access. You can read more about it here
https://developer.android.com/training/data-storage/shared/documents-files
You can just backup your db file to the public Documents directory.
No need for the permissions you mentioned.
Alright so, after a bit of research I found the best solution for myself is as follows:
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS) + File.separator + "foldername"
this doesn't require permissions and works on below and above API 30
This question already has answers here:
Android ACTION_SEND event: "messaging failed to upload attachment"
(2 answers)
Closed 5 years ago.
I am trying to create a Sharing Intent for an Android App to share images to other apps. However, I'm getting this really weird result when implementing this feature.
I have a share button that when I click on the button, it runs the following method:
private void shareIntent() {
Uri currUri = Uri.parse(data.get(pos).getUrl());
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setAction(Intent.ACTION_SEND);
sharingIntent.putExtra(Intent.EXTRA_STREAM, currUri);
sharingIntent.setType("image/jpg");
startActivity(Intent.createChooser(sharingIntent, getResources().getText(R.string.share_to)));
}
data.get(pos).getUrl() returns the URL of a custom class I made that implements Parcelable, and when printing it out, it returns a directory like the following: "/storage/emulated/0/Pictures/primitive/Primitive-79538313.jpg"
The intent works at first, opening the sharing menu. However, when I click on most applications, it either crashes the application or it gives an error... except with Google Photos, which uploads the photo properly to the gallery.
Firstly, I'm wondering what I'm doing wrong to cause this issue in the other apps. Also, I'd like to know if someone has an explanation as to why only Google Photos allows the sharing feature to work, while many of the other apps I've tested do not.
For reference, here are some examples I've run with the sharing intent. When I try to share the image, it crashes Hangouts. It gives a "failed to load image" error message in Snapchat, "Unable to share file" in Slack and Gmail, "Upload was unsuccessful" in Drive, "Messenger was unable to process the file" in, well, Messenger, and "Couldn't load image" in GroupMe. It doesn't load the image in Facebook but doesn't crash nor give an error.
Thank you for any help or feedback you can provide!
EDIT:
This seemed to work without trying to get around App Permissions:
private void shareIntent() {
File imageFile = new File(data.get(pos).getUrl());
Uri uriToImage = FileProvider.getUriForFile(
this, BuildConfig.APPLICATION_ID + ".provider", imageFile);
Intent shareIntent = ShareCompat.IntentBuilder.from(DetailActivity.this)
.setStream(uriToImage)
.getIntent();
shareIntent.setData(uriToImage);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.setType("image/jpeg");
startActivity(Intent.createChooser(shareIntent, "Share image"));
}
Thank you to everyone that responded!
Change your code to this
private void shareIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/jepg");
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+data.get(pos).getUrl()));
startActivity(Intent.createChooser(shareIntent, "Share image"));
}
Add this code in your activity onCreate()
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
i am developing a app in which i want to show only apk files to user so he could select only .apk files from file manager. I found several answers but rest didnt work for me. i tried intent.setType("application/vnd.android.package-archive" Infact i am unable to restrict user even only to images.
here is my code
private void showFileChooser() {
Intent intent = new Intent();
//sets the select file to all types of files
intent.setType("application/vnd.android.package-archive");
//allows to select data and return it
intent.setAction(Intent.ACTION_GET_CONTENT);
//starts new activity to select file and return data
startActivityForResult(Intent.createChooser(intent, "Choose File to Upload.."), PICK_FILE_REQUEST);
}
I'm trying to pick a file via an Intent.
What I tryed till now is this:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, FILE_SELECT_CODE);
But with this, I can only pic Photos with the galery app.
My goal is to pic ANY file via the standard file manager of Android/Samsung.
This didn't work either:
String manufactures = android.os.Build.MANUFACTURER;
if(manufactures.equalsIgnoreCase("samsung"))
{
Intent intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
startActivityForResult(intent, FILE_SELECT_CODE);
}
Thx for your help!
My goal is to pic ANY file via the standard file manager of Android/Samsung.
Android does not have a "standard file manager".
If your minSdkVersion is 19 or higher, you are welcome to use the Storage Access Framework (e.g., ACTION_OPEN_DOCUMENT), which is the closest thing that Android now has to a "standard file manager".
Otherwise, you are limited to whatever ACTION_GET_CONTENT-supporting apps that the user has installed, or creating your own file-selection UI, or using one of many existing libraries for selecting files.