1.简单的示例
//点击下载apk并安装public void button_apk(View view) {//主线程显示提示视图final ProgressDialog progressDialog = new ProgressDialog(this);progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);progressDialog.show();//file对象存放在sd卡中(公有的)apkFile = new File(getExternalFilesDir(null), "update.apk");//启动子线程 下载apk 并显示进度new Thread(new Runnable() {@Overridepublic void run() {try {String path = "http://192.168.1.5:8080/20190313/app-debug.apk";URL url = new URL(path);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setConnectTimeout(5000);connection.setReadTimeout(10000);connection.connect();//得到响应int responseCode = connection.getResponseCode();if (responseCode == 200) {progressDialog.setMax(connection.getContentLength());//文件大小InputStream is = connection.getInputStream();FileOutputStream fos = new FileOutputStream(apkFile);//边读边写byte[] buffer = new byte[1024];int len = -1;while ((len = is.read(buffer)) != -1) {fos.write(buffer, 0, len);//显示下载进度progressDialog.incrementProgressBy(len); //注意设置他的最大值(最大值等于文件大小//SystemClock.sleep(50);}is.close();fos.close();}//下载完成 关闭connection.disconnect();//切换到主线程 启动安装runOnUiThread(new Runnable() {@Overridepublic void run() {progressDialog.dismiss(); //取消精度条//安装apkinstallApk();}});} catch (Exception e) {e.printStackTrace();}}}).start();}//安装apkprivate void installApk() {Intent intent = new Intent("android.intent.action.INSTALL_PACKAGE");intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");startActivity(intent);}
动态获取权限的问题 更美的进度条 等等 这只是个最基础的示例。