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);   
     

 

//判断文件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; 

}

转载于:https://www.cnblogs.com/lee0oo0/archive/2012/06/09/2543574.html

你可能感兴趣的:(Android之在手机上打开文件的方法)