Android DownloadManager下载并安装apk

下载方法:

if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            try {
                //检测是否有写的权限
                int permission = ActivityCompat.checkSelfPermission(this,
                        "android.permission.WRITE_EXTERNAL_STORAGE");

                if (permission != PackageManager.PERMISSION_GRANTED) {
                    ToastUtil.show("请允许读写存储权限,否则APP无法正常运行!");
                    // 没有写的权限,去申请写的权限,会弹出对话框
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } 


// H5中包含下载链接的话让外部浏览器去处理
//                Intent intent = new Intent(Intent.ACTION_VIEW);
//                intent.addCategory(Intent.CATEGORY_BROWSABLE);
//                intent.setData(Uri.parse(url));
//                startActivity(intent);

                //使用手机下载器下载
                String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator +"DownLoadApp.apk";
                File apkFile = new File(path);
                if (apkFile.exists()) {
                    apkFile.delete();
                }
                if(downloadId != 0) {
                    clearCurrentTask(downloadId);
                }

                Uri uri = Uri.parse(url);
                DownloadManager.Request request = new DownloadManager.Request(uri);
                // 设置下载路径和文件名
//                request.setDestinationInExternalPublicDir("download", "DownLoadApp.apk");
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "DownLoadApp.apk");
                //通知栏描述信息
                request.setDescription("下载完成后请点击安装");
                // 设置为可被媒体扫描器找到
//                request.allowScanningByMediaScanner();
                // 设置为可见和可管理
//                request.setVisibleInDownloadsUi(true);
                request.setMimeType("application/vnd.android.package-archive");
                DownloadManager dManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                dManager.enqueue(request);

添加广播进行安装:

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.content.FileProvider;
import android.util.Log;



import java.io.File;



public class DownloadReceiver extends BroadcastReceiver {
    @SuppressLint("NewApi")

    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            installApk(context, id);
        } else if (intent.getAction().equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
            Intent viewDownloadIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
            viewDownloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(viewDownloadIntent);
        }
    }

    private void installApk(Context context, long downloadApkId) {

        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + "DownLoadApp.apk";
        File apkFile = new File(path);
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.N){

            Uri apkUri = FileProvider.getUriForFile(context, "com.gxmokebook.monkebookgx.fileprovider", apkFile);
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.addCategory(Intent.CATEGORY_DEFAULT);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            context.startActivity(install);
        } else {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setType("application/vnd.android.package-archive");
            intent.setData(Uri.fromFile(apkFile));
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            context.startActivity(intent);
        }
    }
}

其他配置文件:

AndroidManifest.xml中添加以下代码:


            
        

在res文件夹下新建file_paths.xml文件:



    
    
    
    
    

 

你可能感兴趣的:(Android)