1. 程式人生 > >android 下載apk後安裝apk(適配android 7.0)

android 下載apk後安裝apk(適配android 7.0)

    為適配7.0以後系統,首先需要在AndroidManifest.xml檔案中application節點下定義provider,如下:

  <provider

         android:name=:"android.support.v4.content.FileProvider"

         android:authorities="com.dlgs.vendor.fileprovider"  //自定義名稱

         android:export="false"

         android:grantUriPermissions="true">

          <meta-data

                 android:name="android.support.FILE_PROVIDER_PATHS"

                 android:resouce="@xml/file_paths"/>   // xml檔案,

</provider>

 

在res下建立xml目錄,在xml目錄下建立file_paths.xml檔案,檔案裡的內容為:

<?xml version="1.0" encoding="utf-8"?>
<!--external-path用來指定Uri共享,name屬性是起的名稱,path屬性的值表示共享的具體路徑,設定空值表示整
個SD卡共享-->
<path xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path=""/>
</path>

 

安裝apk的方法:

    /**
     * 安裝apk
     * @param apkPath apk的絕對路徑
     */
    private void installApk(String apkPath)
    {
        Intent intent = new Intent("android.intent.action.VIEW");
        // 下面這句程式碼一定不能少,不然安裝後不會進入開啟/完成 的選擇頁面
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

       // android 7.0 以後
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N)
        {
            Uri apkUri = FileProvider.getUriForFile(context,            //所在activity的上下文
                                                    "com.dlgs.vendor.fileprovider", //AndroidManifest.xml檔案中provider裡的authorities值
                                                    new File(apkPath));
            // 臨時授權
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri,
                                  "application/vnd.android.package-archive");
        } else
        {

            // android 7.0 以前
            intent.addCategory("android.intent.category.DEFAULT");
            intent.setDataAndType(Uri.parse("file:" + apkPath),
                                  "application/vnd.android.package-archive");
        }
        startActivity(intent);
    }

 注意,一定要新增intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);這句程式碼,不然更新安裝apk後會進入手機桌面;