大家好,发现半年没有更新博客了,最近一直都比较忙,决定在凌晨 英超 阿森纳VS富勒姆 中场休息的时候,给大家分享Android里应用版本更新功能这一块的实现。
一个好的应用软件都是需要好的维护,从初出版本到最后精品,这个过程需要版本不停的更新,那么如何让用户第一时间获取最新的应用安装包呢?那么就要求我们从第一个版本就要实现升级模块这一功能。
自动更新功能的实现原理,就是我们事先和后台协商好一个接口,我们在应用的主Activity里,去访问这个接口,如果需要更新,后台会返回一些数据(比如,提示语;最新版本的url等)。然后我们给出提示框,用户点击开始下载,下载完成开始覆盖安装程序,这样用户的应用就保持最新的拉。
为了让大家容易理解,我像往常一样准备一个小例子,这里为了方便我就省去了和后台交互部分了。步骤分别如下:
第一步:新建一个Android工程命名为:UpdateDemo.代码结构如下图所示:
第二步:新建一个UpdateManager.java类,负责软件更新功能模块,代码如下:
- package com.tutor.update;
-
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.URL;
-
-
- import android.app.AlertDialog;
- import android.app.Dialog;
- import android.app.AlertDialog.Builder;
- import android.content.Context;
- import android.content.DialogInterface;
- import android.content.Intent;
- import android.content.DialogInterface.OnClickListener;
- import android.net.Uri;
- import android.os.Handler;
- import android.os.Message;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.widget.ProgressBar;
-
- public class UpdateManager {
-
- private Context mContext;
-
-
- private String updateMsg = “有最新的软件包哦,亲快下载吧~”;
-
-
- private String apkUrl = “http://softfile.3g.qq.com:8080/msoft/179/24659/43549/qq_hd_mini_1.4.apk”;
-
-
- private Dialog noticeDialog;
-
- private Dialog downloadDialog;
-
- private static final String savePath = “/sdcard/updatedemo/”;
-
- private static final String saveFileName = savePath + “UpdateDemoRelease.apk”;
-
-
- private ProgressBar mProgress;
-
-
- private static final int DOWN_UPDATE = 1;
-
- private static final int DOWN_OVER = 2;
-
- private int progress;
-
- private Thread downLoadThread;
-
- private boolean interceptFlag = false;
-
- private Handler mHandler = new Handler(){
- public void handleMessage(Message msg) {
- switch (msg.what) {
- case DOWN_UPDATE:
- mProgress.setProgress(progress);
- break;
- case DOWN_OVER:
-
- installApk();
- break;
- default:
- break;
- }
- };
- };
-
- public UpdateManager(Context context) {
- this.mContext = context;
- }
-
-
- public void checkUpdateInfo(){
- showNoticeDialog();
- }
-
-
- private void showNoticeDialog(){
- AlertDialog.Builder builder = new Builder(mContext);
- builder.setTitle(“软件版本更新”);
- builder.setMessage(updateMsg);
- builder.setPositiveButton(“下载”, new OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- showDownloadDialog();
- }
- });
- builder.setNegativeButton(“以后再说”, new OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- }
- });
- noticeDialog = builder.create();
- noticeDialog.show();
- }
-
- private void showDownloadDialog(){
- AlertDialog.Builder builder = new Builder(mContext);
- builder.setTitle(“软件版本更新”);
-
- final LayoutInflater inflater = LayoutInflater.from(mContext);
- View v = inflater.inflate(R.layout.progress, null);
- mProgress = (ProgressBar)v.findViewById(R.id.progress);
-
- builder.setView(v);
- builder.setNegativeButton(“取消”, new OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- dialog.dismiss();
- interceptFlag = true;
- }
- });
- downloadDialog = builder.create();
- downloadDialog.show();
-
- downloadApk();
- }
-
- private Runnable mdownApkRunnable = new Runnable() {
- @Override
- public void run() {
- try {
- URL url = new URL(apkUrl);
-
- HttpURLConnection conn = (HttpURLConnection)url.openConnection();
- conn.connect();
- int length = conn.getContentLength();
- InputStream is = conn.getInputStream();
-
- File file = new File(savePath);
- if(!file.exists()){
- file.mkdir();
- }
- String apkFile = saveFileName;
- File ApkFile = new File(apkFile);
- FileOutputStream fos = new FileOutputStream(ApkFile);
-
- int count = 0;
- byte buf[] = new byte[1024];
-
- do{
- int numread = is.read(buf);
- count += numread;
- progress =(int)(((float)count / length) * 100);
-
- mHandler.sendEmptyMessage(DOWN_UPDATE);
- if(numread <= 0){
-
- mHandler.sendEmptyMessage(DOWN_OVER);
- break;
- }
- fos.write(buf,0,numread);
- }while(!interceptFlag);
-
- fos.close();
- is.close();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch(IOException e){
- e.printStackTrace();
- }
-
- }
- };
-
-
-
-
-
-
- private void downloadApk(){
- downLoadThread = new Thread(mdownApkRunnable);
- downLoadThread.start();
- }
-
-
-
-
- private void installApk(){
- File apkfile = new File(saveFileName);
- if (!apkfile.exists()) {
- return;
- }
- Intent i = new Intent(Intent.ACTION_VIEW);
- i.setDataAndType(Uri.parse(“file://” + apkfile.toString()), “application/vnd.android.package-archive”);
- mContext.startActivity(i);
-
- }
- }
package com.tutor.update;</p><p>import java.io.File;</p><p>import java.io.FileOutputStream;</p><p>import java.io.IOException;</p><p>import java.io.InputStream;</p><p>import java.net.HttpURLConnection;</p><p>import java.net.MalformedURLException;</p><p>import java.net.URL;</p><p>import android.app.AlertDialog;</p><p>import android.app.Dialog;</p><p>import android.app.AlertDialog.Builder;</p><p>import android.content.Context;</p><p>import android.content.DialogInterface;</p><p>import android.content.Intent;</p><p>import android.content.DialogInterface.OnClickListener;</p><p>import android.net.Uri;</p><p>import android.os.Handler;</p><p>import android.os.Message;</p><p>import android.view.LayoutInflater;</p><p>import android.view.View;</p><p>import android.widget.ProgressBar;</p><p>public class UpdateManager {</p><p> private Context mContext;</p><p> </p><p> //提示语</p><p> private String updateMsg = "有最新的软件包哦,亲快下载吧~";</p><p> </p><p> //返回的安装包url</p><p> private String apkUrl = "http://softfile.3g.qq.com:8080/msoft/179/24659/43549/qq_hd_mini_1.4.apk";</p><p> </p><p> </p><p> private Dialog noticeDialog;</p><p> </p><p> private Dialog downloadDialog;</p><p> /* 下载包安装路径 */</p><p> private static final String savePath = "/sdcard/updatedemo/";</p><p> </p><p> private static final String saveFileName = savePath + "UpdateDemoRelease.apk";</p><p> /* 进度条与通知ui刷新的handler和msg常量 */</p><p> private ProgressBar mProgress;</p><p> </p><p> private static final int DOWN_UPDATE = 1;</p><p> </p><p> private static final int DOWN_OVER = 2;</p><p> </p><p> private int progress;</p><p> </p><p> private Thread downLoadThread;</p><p> </p><p> private boolean interceptFlag = false;</p><p> </p><p> private Handler mHandler = new Handler(){</p><p> public void handleMessage(Message msg) {</p><p> switch (msg.what) {</p><p> case DOWN_UPDATE:</p><p> mProgress.setProgress(progress);</p><p> break;</p><p> case DOWN_OVER:</p><p> </p><p> installApk();</p><p> break;</p><p> default:</p><p> break;</p><p> }</p><p> };</p><p> };</p><p> </p><p> public UpdateManager(Context context) {</p><p> this.mContext = context;</p><p> }</p><p> </p><p> //外部接口让主Activity调用</p><p> public void checkUpdateInfo(){</p><p> showNoticeDialog();</p><p> }</p><p> </p><p> </p><p> private void showNoticeDialog(){</p><p> AlertDialog.Builder builder = new Builder(mContext);</p><p> builder.setTitle("软件版本更新");</p><p> builder.setMessage(updateMsg);</p><p> builder.setPositiveButton("下载", new OnClickListener() { </p><p> @Override</p><p> public void onClick(DialogInterface dialog, int which) {</p><p> dialog.dismiss();</p><p> showDownloadDialog(); </p><p> }</p><p> });</p><p> builder.setNegativeButton("以后再说", new OnClickListener() { </p><p> @Override</p><p> public void onClick(DialogInterface dialog, int which) {</p><p> dialog.dismiss(); </p><p> }</p><p> });</p><p> noticeDialog = builder.create();</p><p> noticeDialog.show();</p><p> }</p><p> </p><p> private void showDownloadDialog(){</p><p> AlertDialog.Builder builder = new Builder(mContext);</p><p> builder.setTitle("软件版本更新");</p><p> </p><p> final LayoutInflater inflater = LayoutInflater.from(mContext);</p><p> View v = inflater.inflate(R.layout.progress, null);</p><p> mProgress = (ProgressBar)v.findViewById(R.id.progress);</p><p> </p><p> builder.setView(v);</p><p> builder.setNegativeButton("取消", new OnClickListener() { </p><p> @Override</p><p> public void onClick(DialogInterface dialog, int which) {</p><p> dialog.dismiss();</p><p> interceptFlag = true;</p><p> }</p><p> });</p><p> downloadDialog = builder.create();</p><p> downloadDialog.show();</p><p> </p><p> downloadApk();</p><p> }</p><p> </p><p> private Runnable mdownApkRunnable = new Runnable() { </p><p> @Override</p><p> public void run() {</p><p> try {</p><p> URL url = new URL(apkUrl);</p><p> </p><p> HttpURLConnection conn = (HttpURLConnection)url.openConnection();</p><p> conn.connect();</p><p> int length = conn.getContentLength();</p><p> InputStream is = conn.getInputStream();</p><p> </p><p> File file = new File(savePath);</p><p> if(!file.exists()){</p><p> file.mkdir();</p><p> }</p><p> String apkFile = saveFileName;</p><p> File ApkFile = new File(apkFile);</p><p> FileOutputStream fos = new FileOutputStream(ApkFile);</p><p> </p><p> int count = 0;</p><p> byte buf[] = new byte[1024];</p><p> </p><p> do{ </p><p> int numread = is.read(buf);</p><p> count += numread;</p><p> progress =(int)(((float)count / length) * 100);</p><p> //更新进度</p><p> mHandler.sendEmptyMessage(DOWN_UPDATE);</p><p> if(numread <= 0){ </p><p> //下载完成通知安装</p><p> mHandler.sendEmptyMessage(DOWN_OVER);</p><p> break;</p><p> }</p><p> fos.write(buf,0,numread);</p><p> }while(!interceptFlag);//点击取消就停止下载.</p><p> </p><p> fos.close();</p><p> is.close();</p><p> } catch (MalformedURLException e) {</p><p> e.printStackTrace();</p><p> } catch(IOException e){</p><p> e.printStackTrace();</p><p> }</p><p> </p><p> }</p><p> };</p><p> </p><p> /**</p><p> * 下载apk</p><p> * @param url</p><p> */</p><p> </p><p> private void downloadApk(){</p><p> downLoadThread = new Thread(mdownApkRunnable);</p><p> downLoadThread.start();</p><p> }</p><p> /**</p><p> * 安装apk</p><p> * @param url</p><p> */</p><p> private void installApk(){</p><p> File apkfile = new File(saveFileName);</p><p> if (!apkfile.exists()) {</p><p> return;</p><p> } </p><p> Intent i = new Intent(Intent.ACTION_VIEW);</p><p> i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive"); </p><p> mContext.startActivity(i);</p><p> </p><p> }</p><p>}</p><p>
第三步:在MainActivity.java也就是主Activity调用,代码如下:
- package com.tutor.update;
-
- import android.app.Activity;
- import android.os.Bundle;
-
- public class MainAcitivity extends Activity {
-
-
- private UpdateManager mUpdateManager;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
-
- mUpdateManager = new UpdateManager(this);
- mUpdateManager.checkUpdateInfo();
- }
- }
package com.tutor.update;</p><p>import android.app.Activity;</p><p>import android.os.Bundle;</p><p>public class MainAcitivity extends Activity {</p><p> </p><p> private UpdateManager mUpdateManager;</p><p> @Override</p><p> public void onCreate(Bundle savedInstanceState) {</p><p> super.onCreate(savedInstanceState);</p><p> setContentView(R.layout.main);</p><p> </p><p> //这里来检测版本是否需要更新</p><p> mUpdateManager = new UpdateManager(this);</p><p> mUpdateManager.checkUpdateInfo();</p><p> } </p><p>}
第四步:添加程序所用的资源与权限:
下载的时候用到了ProgressBar,所以事先写了一个progress.xml布局文件,代码如下:
- <?xml version=“1.0” encoding=“utf-8”?>
- <LinearLayout
- xmlns:android=“http://schemas.android.com/apk/res/android”
- android:layout_width=“fill_parent”
- android:layout_height=“wrap_content”>
-
- <ProgressBar
- android:id=“@+id/progress”
- android:layout_width=“fill_parent”
- android:layout_height=“wrap_content”
- style=“?android:attr/progressBarStyleHorizontal”
- />
- </LinearLayout>
<?xml version="1.0" encoding="utf-8"?></p><p><LinearLayout</p><p> xmlns:android="http://schemas.android.com/apk/res/android"</p><p> android:layout_width="fill_parent"</p><p> android:layout_height="wrap_content"></p><p> </p><p> <ProgressBar</p><p> android:id="@+id/progress"</p><p> android:layout_width="fill_parent"</p><p> android:layout_height="wrap_content"</p><p> style="?android:attr/progressBarStyleHorizontal"</p><p> /></p><p></LinearLayout></p><p>
下载的时候用到了网络部分,所以要在AndroidManifest.xml中添加网络权限,代码如下:
- <uses-permission android:name=“android.permission.INTERNET” />
<uses-permission android:name="android.permission.INTERNET" />
第五步:运行查看效果如下:
图一:提示有最新包 图二:点击开始下载
图三:下载完开始安装,我这里模拟器空间不足了。
OK~大功告成了,继续看球,阿森纳已经0:1了,希望范大将军救驾!大家晚安~稍后将会为大家分享更多内容,尽请期待!
源代码点击进入==>
来源URL:http://blog.csdn.net/android_tutor/article/details/7015986