美文网首页
android 用其他应用打开文件

android 用其他应用打开文件

作者: Pin_ZL | 来源:发表于2017-06-28 10:16 被阅读0次

目前android大部分手机都有安装wps,有的甚至还会安装其他阅读类的app,比如:华为手机自带华为阅读等等。

这些一系列的应用,以wps为例(稳定、支持的文件格式相对较多):

支持文件类型:.doc  .docx  .xls  .xlsx  .pdf  .ppt  ..pptx  .wps

当然了,如果想要打开mac上的.key或者其他类型文件,wps是不支持这样的格式的。

直接上代码:

/**

* 打开文件

*

*@paramfile

*/

private voidopenOrShareFile(File file,String action) {

try{

if(file ==null|| !file.exists()) {

showTopSnackBar("文件不存在");

return;

}

if(TextUtils.equals(FileUtils.getFileType(file.getName()),".key")) {

showTopSnackBar("此文件类型不支持打开");

return;

}

log("-------------->file path:"+ file.getAbsolutePath());

Intent intent =newIntent();

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

//设置intent的Action属性

intent.setAction(action);

//获取文件file的MIME类型

String type = FileUtils.getMIMEType(file);

//设置intent的data和Type属性。

Uri uri =null;

if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.N) {

uri = FileProvider.getUriForFile(this,BuildConfig.APPLICATION_ID+".provider",file);

}else{

uri = Uri.fromFile(file);

}

log("-------------->open uri:"+ uri);

//添加这一句表示对目标应用临时授权该Uri所代表的文件

intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION

| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

if(action.equals(Intent.ACTION_VIEW)) {

intent.setDataAndType(uri,type);

startActivity(intent);//这里最好try一下,有可能会报错。 //比如说你的MIME类型是打开邮箱,但是你手机里面没装邮箱客户端,就会报错。

}

}catch(Exception e) {

e.printStackTrace();

bugSync("外部打开文件失败",e);

}

}

/**

* 分享文件

*

*@paramfile

*/

private voidshareFile(File file) {

try{

if(file ==null|| !file.exists()) {

showTopSnackBar("文件不存在");

return;

}

log("-------------->file path:"+ file.getAbsolutePath());

Intent intent =newIntent(Intent.ACTION_SEND);

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

//设置intent的data和Type属性。

Uri uri = Uri.fromFile(file);

log("-------------->share uri:"+ uri);

//添加这一句表示对目标应用临时授权该Uri所代表的文件

intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION

| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

intent.putExtra(Intent.EXTRA_STREAM,uri);

intent.setType("*/*");

startActivity(Intent.createChooser(intent,"Alpha Share"));

}catch(Exception e) {

e.printStackTrace();

bugSync("外部分享文件失败",e);

}

}

特别注意粗体+斜体部分,兼容各种手机版本。

相关文章

网友评论

      本文标题:android 用其他应用打开文件

      本文链接:https://www.haomeiwen.com/subject/uvaycxtx.html