在Android手機上打開文件的方法
//File指的是文件路徑
private void openFile(File file){
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//設置intent的Action屬性
intent.setAction(Intent.ACTION_VIEW);
//獲取文件file的MIME類型
String type = getMIMEType(file);
//設置intent的data和Type屬性。
intent.setDataAndType(Uri.fromFile(file), type);
//跳轉
startActivity(intent);
}
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//設置intent的Action屬性
intent.setAction(Intent.ACTION_VIEW);
//獲取文件file的MIME類型
String type = getMIMEType(file);
//設置intent的data和Type屬性。
intent.setDataAndType(Uri.fromFile(file), type);
//跳轉
startActivity(intent);
}
//判斷文件MimeType的方法
private String getMimeType(File f){
String type="";
String fName = f.getName();
//取得擴展名
String end = fName.substring(fName.lastIndexOf(".")+1 , fName.length()).toLowerCase());
//根據擴展名決定Mime類型
if(end.equals("m4a") || end.equals("mp3") || end.equals("mid") || end.equals("xmf") || end.equals("ogg") || end.equals("wav")){
type = "audio";
}
else if(end.equals("3gp") || end.equals("mp4")){
type = "video";
}
else if(end.equals("jpg") || end.equals("gif") || end.equals("png") || end.equals("jpeg") || end.equals("bmp")){
type = "image";
}
else if(end.equals("apk")){
//打開安裝apk程序 , 需要在AndroidManifest中注冊 android.permission.INSTALL_PACKAGES
type = "application/vnd.android.package-archive";
}
return type;
}
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!