1. 程式人生 > >android app 更新下載安裝 適配android 7.0

android app 更新下載安裝 適配android 7.0

public class UpdataService extends Service {
    public UpdataService() {
    }

    /**
     * 安卓系統下載類
     **/
    private DownloadManager manager;
    /**
     * 接收下載完的廣播
     **/
    private DownloadCompleteReceiver receiver;
    private String url;
    private String DOWNLOADPATH = "/download/";//下載路徑,如果不定義自己的路徑,6.0的手機不自動安裝

    /**
     * 初始化下載器
     **/
    private void initDownManager() {
        manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        receiver = new DownloadCompleteReceiver();
        //設定下載地址
        DownloadManager.Request down = new DownloadManager.Request(Uri.parse(url));
        // 設定允許使用的網路型別,這裡是行動網路和wifi都可以
        down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
                | DownloadManager.Request.NETWORK_WIFI);
        down.setAllowedOverRoaming(false);
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
        down.setMimeType(mimeString);
        // 下載時,通知欄顯示途中
        down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        // 顯示下載介面
        down.setVisibleInDownloadsUi(true);
        // 設定下載後文件存放的位置
        down.setDestinationInExternalPublicDir(DOWNLOADPATH, "app-release.apk");
        down.setTitle("****");
        // 將下載請求放入佇列
        manager.enqueue(down);
        //註冊下載廣播
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }
    @Overrid
    public int onStartCommand(Intent intent, int flags, int startId) {

        url = intent.getStringExtra("downloadurl");
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + DOWNLOADPATH + "app-release.apk";
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        try {
            // 呼叫下載
            initDownManager();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "下載失敗", Toast.LENGTH_SHORT).show();
        }
        return Service.START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public void onDestroy() {
        if (receiver != null)
            // 登出下載廣播
            unregisterReceiver(receiver);
        super.onDestroy();
    }

    // 接受下載完成後的intent
    class DownloadCompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            //判斷是否下載完成的廣播
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                //獲取下載的檔案id
                long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (manager.getUriForDownloadedFile(downId) != null) {
                    //自動安裝apk
                    installAPK(manager.getUriForDownloadedFile(downId), context);
                    //installAPK(context);
                } else {
                    Toast.makeText(context, "下載失敗", Toast.LENGTH_SHORT).show();
                }
                //停止服務並關閉廣播
                UpdataService.this.stopSelf();
            }
        }

        private void installAPK(Uri apk, Context context) {
            if (Build.VERSION.SDK_INT < 23) {
                Intent intents = new Intent();
                intents.setAction(Intent.ACTION_VIEW);
//                intents.addCategory("android.intent.category.DEFAULT");
                intents.setDataAndType(apk, "application/vnd.android.package-archive");
                intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intents);
            } else if (Build.VERSION.SDK_INT >= 24) {
                install(context);
            } else {
                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + DOWNLOADPATH + "app-release.apk");
                if (file.exists()) {
                    openFile(file, context);
                } else {
                }
            }
        }

        /**
         * android7.0之後的更新
         * 通過隱式意圖呼叫系統安裝程式安裝APK
         */
        public void install(Context context) {
            File file = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                    , "app-release.apk");
            Intent intent = new Intent(Intent.ACTION_VIEW);
            //引數1 上下文, 引數2 Provider主機地址 和配置檔案中保持一致   引數3  共享的檔案
            Uri apkUri =
                    FileProvider.getUriForFile(context, "cn.jiandao.global.fileprovider", file);
            intent.addCategory("android.intent.category.DEFAULT");
            // 由於沒有在Activity環境下啟動Activity,設定下面的標籤
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //新增這一句表示對目標應用臨時授權該Uri所代表的檔案
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            context.startActivity(intent);
        }

        private void installAPK(Context context) {
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + DOWNLOADPATH + "huijuquanqiu.apk");
            if (file.exists()) {
                openFile(file, context);
            } else {
                Toast.makeText(context, "下載失敗", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * android6.0之後的升級更新
     *
     * @param file
     * @param context
     */
    public void openFile(File file, Context context) {
        Intent intent = new Intent();
        intent.addFlags(268435456);
        intent.setAction("android.intent.action.VIEW");
        String type = getMIMEType(file);
        intent.setDataAndType(Uri.fromFile(file), type);
        try {
            context.startActivity(intent);
        } catch (Exception var5) {
            var5.printStackTrace();
            Toast.makeText(context, "沒有找到開啟此類檔案的程式", Toast.LENGTH_SHORT).show();
        }
    }

    public String getMIMEType(File var0) {
        String var1 = "";
        String var2 = var0.getName();
        String var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase();
        var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3);
        return var1;
    }

}

3.這是後臺下載app,並且安裝的後臺服務

(1)開啟服務,初始化下載地址

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        url = intent.getStringExtra("downloadurl");
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + DOWNLOADPATH + "app-release.apk";
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        try {
            // 呼叫下載
            initDownManager();
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(), "下載失敗", Toast.LENGTH_SHORT).show();
        }
        return Service.START_NOT_STICKY;
    }

(2)初始化下載方法,並且在通知欄設定下載進度條,並且註冊廣播接收者

/**
     * 初始化下載器
     **/
    private void initDownManager() {
        manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
        receiver = new DownloadCompleteReceiver();
        //設定下載地址
        DownloadManager.Request down = new DownloadManager.Request(Uri.parse(url));
        // 設定允許使用的網路型別,這裡是行動網路和wifi都可以
        down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
                | DownloadManager.Request.NETWORK_WIFI);
        down.setAllowedOverRoaming(false);
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
        down.setMimeType(mimeString);
        // 下載時,通知欄顯示途中
        down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        // 顯示下載介面
        down.setVisibleInDownloadsUi(true);
        // 設定下載後文件存放的位置
        down.setDestinationInExternalPublicDir(DOWNLOADPATH, "app-release.apk");
        down.setTitle("****");
        // 將下載請求放入佇列
        manager.enqueue(down);
        //註冊下載廣播
        registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

(3)啟動廣播接收者,並開啟自動安裝app

// 接受下載完成後的intent
    class DownloadCompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {

            //判斷是否下載完成的廣播
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                //獲取下載的檔案id
                long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
                if (manager.getUriForDownloadedFile(downId) != null) {
                    //自動安裝apk
                    installAPK(manager.getUriForDownloadedFile(downId), context);
                    //installAPK(context);
                } else {
                    Toast.makeText(context, "下載失敗", Toast.LENGTH_SHORT).show();
                }
                //停止服務並關閉廣播
                UpdataService.this.stopSelf();
            }
        }

        private void installAPK(Uri apk, Context context) {
            if (Build.VERSION.SDK_INT < 23) {
                Intent intents = new Intent();
                intents.setAction(Intent.ACTION_VIEW);
//                intents.addCategory("android.intent.category.DEFAULT");
                intents.setDataAndType(apk, "application/vnd.android.package-archive");
                intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intents);
            } else if (Build.VERSION.SDK_INT >= 24) {
                install(context);
            } else {
                File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + DOWNLOADPATH + "app-release.apk");
                if (file.exists()) {
                    openFile(file, context);
                } else {
                }
            }
        }

        /**
         * android7.0之後的更新
         * 通過隱式意圖呼叫系統安裝程式安裝APK
         */
        public void install(Context context) {
            File file = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                    , "app-release.apk");
            Intent intent = new Intent(Intent.ACTION_VIEW);
            //引數1 上下文, 引數2 Provider主機地址 和配置檔案中保持一致   引數3  共享的檔案
            Uri apkUri =
                    FileProvider.getUriForFile(context, "cn.jiandao.global.fileprovider", file);
            intent.addCategory("android.intent.category.DEFAULT");
            // 由於沒有在Activity環境下啟動Activity,設定下面的標籤
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //新增這一句表示對目標應用臨時授權該Uri所代表的檔案
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            context.startActivity(intent);
        }

        private void installAPK(Context context) {
            File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + DOWNLOADPATH + "huijuquanqiu.apk");
            if (file.exists()) {
                openFile(file, context);
            } else {
                Toast.makeText(context, "下載失敗", Toast.LENGTH_SHORT).show();
            }
        }
    }

(4)android6.0之後的安裝

/**
     * android6.0之後的升級更新
     *
     * @param file
     * @param context
     */
    public void openFile(File file, Context context) {
        Intent intent = new Intent();
        intent.addFlags(268435456);
        intent.setAction("android.intent.action.VIEW");
        String type = getMIMEType(file);
        intent.setDataAndType(Uri.fromFile(file), type);
        try {
            context.startActivity(intent);
        } catch (Exception var5) {
            var5.printStackTrace();
            Toast.makeText(context, "沒有找到開啟此類檔案的程式", Toast.LENGTH_SHORT).show();
        }
    }

    public String getMIMEType(File var0) {
        String var1 = "";
        String var2 = var0.getName();
        String var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase();
        var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3);
        return var1;
    }

(5)主要是android 7.0的配置,android7.0之後的安裝

/**
         * android7.0之後的更新
         * 通過隱式意圖呼叫系統安裝程式安裝APK
         */
        public void install(Context context) {
            File file = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
                    , "app-release.apk");
            Intent intent = new Intent(Intent.ACTION_VIEW);
            //引數1 上下文, 引數2 Provider主機地址 和配置檔案中保持一致   引數3  共享的檔案
            Uri apkUri =
                    FileProvider.getUriForFile(context, "cn.xxx.xxx.fileprovider", file);
            intent.addCategory("android.intent.category.DEFAULT");
            // 由於沒有在Activity環境下啟動Activity,設定下面的標籤
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            //新增這一句表示對目標應用臨時授權該Uri所代表的檔案
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            context.startActivity(intent);
        }
在AndroidManifest.xml進行配置
<application
         ....>
        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="cn.xxx.xxx.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths" />
        </provider>
</application>
然後再建立一個資原始檔file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <root-path path="" name="download" />
</paths>