Start Activity Using ACTION_VIEW Intent For Selected MIME Type In Android

As shown in previous post, we are now able to get file extension and MIME Type. This example shows how you can start another activity with intent of ACTION_VIEW to view the file according to the detected MIME Type.

Algorithm:

1.) Create a new project by File-> New -> Android Project name it StartActivityWithMIMEType.

2.) Write following permissions into android manifest.xml:

 

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 

3.) Run for output.

Steps:

1.) Create a project named StartActivityWithMIMEType and set the information as stated in the image.

Build Target: Android 4.4
Application Name: StartActivityWithMIMEType
Package Name: com.example. StartActivityWithMIMEType
Activity Name: StartActivityWithMIMEType

actionview1

2.) Open StartActivityWithMIMEType.java file and write following code there:

 

package com.example.startactivitywithmimetype;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class StartActivityWithMIMEType extends ListActivity {

private List<String> fileList = new ArrayList<String>();

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

File root = new File(Environment
.getExternalStorageDirectory()
.getAbsolutePath());
ListDir(root);

}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
File selected = new File(fileList.get(position));
if(selected.isDirectory()){
ListDir(selected);
}else {
Uri selectedUri = Uri.fromFile(selected);
String fileExtension
= MimeTypeMap.getFileExtensionFromUrl(selectedUri.toString());
String mimeType
= MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension);

Toast.makeText(StartActivityWithMIMEType.this,
"FileExtension: " + fileExtension + "n" +
"MimeType: " + mimeType,
Toast.LENGTH_LONG).show();

//Start Activity to view the selected file
Intent intent;
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(selectedUri, mimeType);
startActivity(intent);

}
}

void ListDir(File f){
File[] files = f.listFiles();
fileList.clear();
for (File file : files){
fileList.add(file.getPath());
}

ArrayAdapter<String> directoryList
= new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, fileList);
setListAdapter(directoryList);
}
}

 

3.) Compile and build the project.

Output

actionview2

actionview3

actionview4