Android 下载并安装APK

2020-04-07  本文已影响0人  Williammmm

1.申请权限

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />

2.下载apk

try {
                            //读取文件
                            InputStream inputStream = body.byteStream();
                            //创建文件夹
                            File dirPath = Environment.getExternalStorageDirectory();
                            File dirsFile = new File(dirPath.getPath()+DOWNLOAD_PATH);
                            if (!dirsFile.exists()){
                                dirsFile.mkdirs();
                            }
                            String fileName = "quickFlight.apk";
                            File file = new File(dirsFile.toString(), fileName);
                            mApkPath = file.toString();
                            FileOutputStream outputStream = new FileOutputStream(file);

                            byte[] bytes = new byte[4096];
                            int len=0;
                            //循环读取文件的内容,把他放到新的文件目录里面
                            while ((len=inputStream.read(bytes))!= -1){
                                outputStream.write(bytes,0,len);
                                long length = file.length();
                                //获取下载的大小,并把它传给页面
                                int progress= (int) (length*100/ mContentLength);
                                mProgressBar.setProgress(progress);
//                                Log.i(TAG, "onNext: =====>>"+progress);
                            }
                            outputStream.close();
                            inputStream.close();
                            mContentLength =0;
                        } catch (Exception e) {
                            e.printStackTrace();
                            mContentLength = 0;
                        }
上一篇下一篇

猜你喜欢

热点阅读