Pick a file from an SD card using Intent
Asked Answered
B

2

7

Does Android have a way to browse and pick any file from an SD card using intents?

Something like:

String uri = (Environment.getExternalStorageDirectory()).getAbsolutePath();
Intent i = new Intent(Intent.ACTION_PICK, Uri.parse(uri));

I am trying to send a file to other devices using Bluetooth. I can send if I give the full path of the file name in my code. I want my users to pick the file that should be send.

Belford answered 2/4, 2014 at 9:25 Comment(0)
L
9

You can use the following code:

Intent mediaIntent = new Intent(Intent.ACTION_GET_CONTENT);
mediaIntent.setType("video/*"); // Set MIME type as per requirement
startActivityForResult(mediaIntent,REQUESTCODE_PICK_VIDEO);

Then you can get the path in onActivityResult:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == REQUESTCODE_PICK_VIDEO
            && resultCode == Activity.RESULT_OK) {
        Uri videoUri = data.getData();
        Log.d("", "Video URI= " + videoUri);
    }
}
Liner answered 2/4, 2014 at 9:30 Comment(4)
If I set mediaIntent.setType("video/*"), it is opening galary to browse images and videos. I want to do a common search where I should pick any file. It can music file, apk file and can be anything. Is it possible ?Belford
then use setType("/")Liner
But it says android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.GET_CONTENT typ=/ }Belford
use setType("*/*"); in order to be able to pick any file typeBuyer
L
5

For general browsing use this (e.g. Music file):

Intent intent = new Intent();
intent.setType("*/*");
if (Build.VERSION.SDK_INT < 19) {
    intent.setAction(Intent.ACTION_GET_CONTENT);
    intent = Intent.createChooser(intent, "Select file");
} else {
    intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    String[] mimetypes = { "audio/*", "video/*" };
    intent.putExtra(Intent.EXTRA_MIME_TYPES, mimetypes);
}
startActivityForResult(intent, Constants.REQUEST_BROWSE);

And receive the browsed data here:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == Constants.REQUEST_BROWSE
            && resultCode == Activity.RESULT_OK && data != null) {
        Uri uri = data.getData();
        if (uri != null) {
            // TODO: handle your case
        }
    }
}
Lagoon answered 30/4, 2015 at 7:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.