Android APK 安装/更新问题

来源:互联网 发布:卫浴安装工接单软件 编辑:程序博客网 时间:2024/06/06 00:49
    这几天我一直在着力解决更新安装的问题,在网上找了一大圈之后,有效的链接不过几种,经过梳理之后,得出:
1,早期的安装方式(我们现用的):下载文件,调用系统来进行安装,关键代码:
Intent intents = new Intent();
 intent.setAction(Intent.ACTION_VIEW);(重点一)
intents.addCategory("android.intent.category.DEFAULT");
intents.setType("application/vnd.android.package-archive");
intents.setData(uri);(uri: 文件路径 重点二)
intents.setDataAndType(uri,"application/vnd.android.package-archive");
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intents);


2, 6.0之后,部分系统调用此方法会报错,关键原因是6.0下不识别重点一这个action,后来在网上查到一个解决方法:调用系统去打开APK文件,系统在打开这个文件时,会自动根据文件类型来选择相应的打开方法,比如在Window系统下双击打开txt文件、word文件,系统会自动调用写字板、Office等等,这样就可避开上述问题。
  关键代码如下:
public void openFile(Context context,File file) {  //file APK文件
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        String mimeType = getMIMEType(file);
        intent.setDataAndType(Uri.fromFile(file), mimeType);
        context.startActivity(intent);
    }


//根据文件来获取打开文件的类型  存在获取的文件类型与(1)中的"application/vnd.android.package-archive" 相同的情况
    public String getMIMEType(File file) {
        String type = "";
        String name = file.getName();
        String temp = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase();//获取文件后缀
        type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(temp);//根据后缀来得到读取文件类型
        return type;
    }


  3,本以为事件就这么结束了,后来我在看了文章的评论中说部分Android 7.0 系统调用这个方法不行。为此我特意在7.0的模拟器(可以把他当做官方系统)上试了一下,确实是不行。原因是7.0后谷歌做了更严格的安全认证,第一步中的重点二发生了变化,官方根据此uri找不到文件,安装失败。
  文件路径一般为"file://"开头,而7.0下,Android 框架执行的 StrictMode,API 禁止向您的应用外公开 file://URI;若一定要共享,那么采用"content://"URI,并授予 URI 临时访问权限。
  为了获取正常的可访问地址,采用了新的 FileProvider类。
  呈现到代码里,重点如下:
  //7.0
if (Build.VERSION.SDK_INT >= 24) {
        Uri uri = null;
        try {
            uri = FileProvider.getUriForFile(Welcome.this, "com.bonc.mobile.hbmclient.fileprovider", file);  // 第一个参数:上下文,第二个参数:自定义授权属性,需与xml里配置相同,参数三:文件。
        } catch (Exception e) {
            e.printStackTrace();
        }
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //授予临时权限
        intent.setDataAndType(uri, mimeType);
} else {
        intent.setDataAndType(Uri.fromFile(file), mimeType);
}


其他部分与(2)相同,这样,在7.0下就可以正常安装了。

关于FileProvider的使用及注意事项可参考 http://www.jianshu.com/p/3f9e3fc38eae,这个说的就比较详细。





0 0
原创粉丝点击