Android之APK的下载安装

来源:互联网 发布:centos phpbrew 编辑:程序博客网 时间:2024/05/17 02:05
功能描述: 
1. 下载远程服务器端的APK文件 
2. 同步显示下载进度
3. 下载完成自动安装


关键技术点:
1. SD卡文件读写

2. ProgressDialog的使用

3. 分线程请求网络

4. 安装APK

要下载的APK要提前安装到服务器的WEB内容中

public void downloadAPK(View v){//1.启动主线程,显示提示视图:ProgressDialogfinal ProgressDialog dialog = new ProgressDialog(this);dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);dialog.show();//准备用于保存APK文件的File对象:/storage/sdcard/Android/package_name/files/xxx.apkapkFile = new File(getExternalFilesDir(null),"update.apk");//2.启动分线程,请求下载APK文件,下载过程中显示下载进度new Thread(new Runnable() {@Overridepublic void run() {try {// 1).得到连接对象String path = "http://192.168.51.65:8080/web/ActivityDemo.apk";URL url = new URL(path);HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 2).设置//connection.setRequestMethod("GET");默认connection.setConnectTimeout(5000);connection.setReadTimeout(1000);// 3).连接connection.connect();// 4).请求并得到响应码200int responseCode = connection.getResponseCode();if(responseCode==200){//设置dialog的最大进度dialog.setMax(connection.getContentLength());// 5).得到包含APK文件数据的InputStreamInputStream is = connection.getInputStream();// 6).创建指向apkFile的FileOutputStreamFileOutputStream 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() {public void run() {dialog.dismiss();installAPK();}});} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}).start();}

/** * 启动安装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);}


0 0
原创粉丝点击