下载功能介绍,首先弹出一个进度对话窗,进度随着文件的下载,进度条渐进变化。
1. 定义file文件。
2.主线程显示进度框。 a)定义一个进度对话框,b)设置风格,c)显示show
3.取得文件路径,为下一步input 和output 做准备。
4.启动子线程。详细见注释。
5.完成后,关闭。
6.启动另一个intent,这个是安装程序,是android的自带的安装打包程序。是从android的源码里,packageinstaller里的manifest清单文件中取得的。固定写法。
private File apkFile; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void downloadAPK(View v) { //1). 主线程, 显示提示视图: ProgressDialog final ProgressDialog dialog = new ProgressDialog(this); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.show(); //准备用于保存APK文件的File对象 : /storage/sdcard/Android/package_name/files/xxx.apk apkFile = new File(getExternalFilesDir(null), "update.apk"); //2). 启动分线程, 请求下载APK文件, 下载过程中显示下载进度 new Thread(new Runnable() { @Override public void run() { try { //1. 得到连接对象 String path = "http://192.168.10.165:8080/Web_Server/L04_DataStorage.apk"; URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //2. 设置 //connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.setReadTimeout(10000); //3. 连接 connection.connect(); //4. 请求并得到响应码200 int responseCode = connection.getResponseCode(); if(responseCode==200) { //设置dialog的最大进度 dialog.setMax(connection.getContentLength()); //5. 得到包含APK文件数据的InputStream InputStream is = connection.getInputStream(); //6. 创建指向apkFile的FileOutputStream FileOutputStream fos = new FileOutputStream(apkFile); //7. 边读边写 byte[] buffer = new byte[1024]; int len = -1; while((len=is.read(buffer))!=-1) { fos.write(buffer, 0, len); //8. 显示下载进度 dialog.incrementProgressBy(len); //休息一会(模拟网速慢) //Thread.sleep(50); SystemClock.sleep(50); } fos.close(); is.close(); } //9. 下载完成, 关闭, 进入3) connection.disconnect(); //3). 主线程, 移除dialog, 启动安装 runOnUiThread(new Runnable() { @Override public void run() { dialog.dismiss(); installAPK(); } }); } catch (Exception e) { e.printStackTrace(); } } }).start(); //09-05 12:59:20.553: I/ActivityManager(1179): Displayed com.android.packageinstaller/.PackageInstallerActivity: +282ms } /** * 启动安装APK */ private void installAPK() { Intent intent = new Intent("android.intent.action.INSTALL_PACKAGE"); intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive"); startActivity(intent); }