downloadmanager 7.0, 8.0 다운로드 완료 후 자동 설치 (연습)

9749 단어
zz 는 연습 일 뿐 미 비 한 점 이 많다.
(1) xml 의 provider

    

(2) manifest 등록 및 권한











!주: 다른 fileprovider 와 의 충돌 을 방지 하기 위해 자신의 클래스 계승 Fileprovider 를 실현 합 니 다. ,name 의 주 소 를 이 자바 파일 이 있 는 위치 로 설정 합 니 다.

    

자바 코드:
public class DownLoadUtils {
    private DownloadManager mDownloadManager;
    private DownloadManager.Request mRequest;
    private Context mContext;
    private Builder mBuilder;
    private long downloadId;
    private Cursor cursor;
    private BroadcastReceiver mBroadcastReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            checkStatus();
        }
    };

    public DownLoadUtils(Context context, Builder builder) {
        mContext = context;
        this.mBuilder=builder;
    }

    public void createDownload() throws DownLoadException {
        if (haveit()){
            return;
        }
        Log.e("already:","createdDownload");
        mDownloadManager= (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        if (TextUtils.isEmpty(mBuilder.getFileUrl())){
            throw new DownLoadException("file path is null");
        }
        mRequest=new DownloadManager.Request(Uri.parse(mBuilder.getFileUrl()));

        //                          subpath:        ,       
        if (TextUtils.isEmpty(mBuilder.getFileName())){
            throw new DownLoadException("file name is null");
        }
        mRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,mBuilder.getFileName());

        mRequest.setAllowedOverRoaming(mBuilder.getAllowedOverRoaming());
        //           ,        wifi   
        mRequest.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
        //      MIME    。                 。
        mRequest.setMimeType("application/vnd.android.package-archive");
        //     
        mRequest.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        mRequest.setTitle(mBuilder.getNotificationTitle());
        mRequest.setDescription(mBuilder.getNotificationTitle());
        downloadId=mDownloadManager.enqueue(mRequest);
        mContext.registerReceiver(mBroadcastReceiver,new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }
    /**
     *       
     */
    private void checkStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(downloadId);
        cursor = mDownloadManager.query(query);
//        cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
        if (cursor.moveToFirst()) {
            int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                //    
                case DownloadManager.STATUS_PAUSED:
                    break;
                //    
                case DownloadManager.STATUS_PENDING:
                    break;
                //    
                case DownloadManager.STATUS_RUNNING:
                    break;
                //    
                case DownloadManager.STATUS_SUCCESSFUL:
                    File apkFile =
                            new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),mBuilder.getFileName());
                    installAPK(apkFile);
                    break;
                //    
                case DownloadManager.STATUS_FAILED:
                    Toast.makeText(mContext.getApplicationContext(), "    ", Toast.LENGTH_SHORT).show();
                    break;
            }
        }

        cursor.close();
    }
    private boolean haveit(){
        File apkFile =
                new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),mBuilder.getFileName());
        if (apkFile.exists()){
            installAPK(apkFile);
            return true;
        }else {
            return false;
        }

    }
    private void installAPK(File apkFile) {


        Log.e("filepath:",apkFile.getPath());
        Log.e("filename:",apkFile.getName());
        Log.e("fileAbspath:",apkFile.getAbsolutePath());
        Log.e("filesize",apkFile.length()+"");
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(mContext,"com.hskj.education.myapplication.DownloadManagerProvider", apkFile);
            Log.e("apkUri:",apkUri.toString());
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
        }
        mContext.startActivity(intent);


    }

    public static class Builder{
        //       
        private String fileName;
        //   file Url
        private String fileUrl;
        //         
        private String saveFilePath;
        //  apk     titie
        private String notificationTitle;
        //  apk         
        private String notificationShowText;
        //                 。     ,    。
        private boolean allowedOverRoaming=true;

        public String getFileName() {
            return fileName;
        }

        public Builder setFileName(String fileName) {
            this.fileName = fileName;
            return this;
        }
        public boolean getAllowedOverRoaming() {
            return allowedOverRoaming;
        }

        public Builder setAllowedOverRoaming(boolean allowedOverRoaming) {
            this.allowedOverRoaming = allowedOverRoaming;
            return this;
        }
        public String getFileUrl() {
            return fileUrl;
        }

        public Builder setFileUrl(String fileUrl) {
            this.fileUrl = fileUrl;
            return this;
        }

        public String getSaveFilePath() {
            return saveFilePath;
        }

        public Builder setSaveFilePath(String saveFilePath) {
            this.saveFilePath = saveFilePath;
            return this;
        }

        public String getNotificationTitle() {
            return notificationTitle;
        }

        public Builder setNotificationTitle(String notificationTitle) {
            this.notificationTitle = notificationTitle;
            return this;
        }

        public String getNotificationShowText() {
            return notificationShowText;
        }

        public Builder setNotificationShowText(String notificationShowText) {
            this.notificationShowText = notificationShowText;
            return this;
        }

        public DownLoadUtils create(Context context){
            return new DownLoadUtils(context,this);
        }
    }

    public class DownLoadException extends Exception {
        public DownLoadException(String message) {
            super(message);
        }
        public DownLoadException(String message, Throwable cause) {
            super(message,cause);
        }
    }
}

사용법:
final RxPermissions rxPermissions = new RxPermissions(TestActivity.this);
rxPermissions
        .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.REQUEST_INSTALL_PACKAGES)
        .subscribe(new Consumer() {
            @Override
            public void accept(Permission granted) throws Exception {
                if (granted.name.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    //WRITE_EXTERNAL_STORAGE,permission.granted=true

                    try {
                        new DownLoadUtils
                                .Builder()
                                .setAllowedOverRoaming(false)
                                .setFileName("    ")
                                .setFileUrl("http://xxxxxxxxx.apk")
                                .setNotificationTitle("  ")
                                .setNotificationShowText("   ")
                                .create(TestActivity.this).createDownload();
                    } catch (DownLoadUtils.DownLoadException e) {
                        e.printStackTrace();
                    }
                }

            }
        });

좋은 웹페이지 즐겨찾기