How to browse files for processing

As an android developer, you may at some point have to implement a way for users to choose files locally. Perhaps for file uploading or choosing a song to play.  The easiest way to handle this is using the storage access framework.

Android 5.0 extended this framework with  the OPEN_DOCUMENT_TREE intent. As of now, however, this only works for 5.0, so this tutorial will be focusing on using the OPEN_DOCUMENT intent.

Unfortunately, the OPEN_DOCUMENT method isn’t supported for versions 4.3 and below so you might consider checking the devices SDK version using Build.VERSION to decide whether to use this method or to use the PICK or GET_CONTENT methods, like so:

if(Build.VERSION.SDK_INT >= 19){
    //use this method
    //use a different method



We’ll start with a minimal layout containing a single button to launch the browser.

<RelativeLayout xmlns:android=""
tools:context="com.example.filebrowser.MainActivity" >

android:text="Launch" />


Now we can write the function to launch the browser.

public void performFileSearch(){
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.setType("*/*");    //Note: This can be changed to filter specific MIME types
    startActivityForResult(intent, 42);    //Note: 42 can be any number as long as it matches in onActivityResult

The parameter for the function on line 4 i the MIME type for files you are looking for. So if you want to make sure the user choose an image, change it to “image/*”. If you want the user to choose an audio file, change it to “audio/*”. And so on. The asterisk(*) simply means “all” in this context. Here is a list of different MIME types for reference.

Now we can call that method from the button:

//in onCreate method
Button startButton = (Button) findViewById(;
startButton.setOnClickListener(new OnClickListener(){
    public void onClick(View v) {

Now we just have to decide what to do when a file is selected.

public void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    if (requestCode == 42 && resultCode == Activity.RESULT_OK) {
        // Note: the 42 above can be any number as long as it matches in
        //  the startActivityForResult call in performFileSearch()
        Uri uri = null;
        if (resultData != null) {
            uri = resultData.getData();
            //use the URI

And now you can use the URI to play an audio file, view an image, upload the file to  a database, or whatever you plan to implement.