取得MIME之後再搭配Intent即可根據MIME Type開啟應用程式。
public static String getMIMEType(Uri uri)
{
String mimeType = null;
if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
mimeType = SingletonApplication.getInstance().getContentResolver().getType(uri);
} else {
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
MimeTypeMap.getFileExtensionFromUrl(uri.toString()).toLowerCase());
}
return mimeType;
}
注意參數Uri 的使用如下
File externalStorageDirectoryFilePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),”/readme.docx”);
Log.d(TAG,”File MIME:”+getMIMEType(Uri.fromFile(externalStorageDirectoryFilePath));
其中 externalStorageDirectoryFilePath.getAbsolutePath()) 為回傳外部儲存裝置的目錄路徑,
參數Environment.DIRECTORY_DOCUMENTS為指定回傳外部儲存裝置的目錄路徑的
Documents目錄路徑。因此externalStorageDirectoryFilePath.getAbsolutePath()); 回傳路徑如下
/storage/emulated/0/Documents/readme.docx
docx的MIME為
application/vnd.openxmlformats-officedocument.wordprocessingml.document
txt的MIME為
text/plain
接著使用Intent開啟檔案
File externalStorageDirectoryFilePath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),”/readme.docx”);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(externalStorageDirectoryFilePath,
getMIMEType(Uri.fromFile(externalStorageDirectoryFilePath)));
activity.getContext().startActivity(intent);