Android实现APP⾃动更新功能
现在⼀般的android软件都是需要不断更新的,当你打开某个app的时候,如果有新的版本,它会提⽰你有新版本需要更新。该⼩程序实现的就是这个功能。
该⼩程序的特点是,当有更新时,会弹出⼀个提⽰框,点击确定,则在通知来创建⼀个进度条进⾏下载,点击取消,则取消更新。
以下是详细代码:
1.创建布局⽂件l,⽤于在通知栏⽣成⼀个进度条和下载图标。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="schemas.android/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="3dp" >
<ImageView
android:id="@+id/notificationImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@android:drawable/stat_sys_download" />
<TextView
android:id="@+id/notificationTitle"
android最新版android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_toRightOf="@id/notificationImage"
android:paddingLeft="6dp"
android:textColor="#FF000000" />
<TextView
android:id="@+id/notificationPercent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/notificationImage"
android:paddingTop="2dp"
android:textColor="#FF000000" />
<ProgressBar
android:id="@+id/notificationProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@id/notificationTitle"
android:layout_alignParentRight="true"
android:layout_alignTop="@id/notificationPercent"
android:layout_below="@id/notificationTitle"
android:paddingLeft="6dp"
android:paddingRight="3dp"
android:paddingTop="2dp" />
</RelativeLayout>
2.创建AppContext类,该类继承⾃Application。
st.application;
import android.app.Application;
t.Context;
fig.Config;
public class AppContext extends Application {
private static AppContext appInstance;
private Context context;
public static AppContext getInstance() {
return appInstance;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
appInstance = this;
context = BaseContext();
//  // 获取当前版本号
//  try {
//  PackageInfo packageInfo = getApplicationContext()
//    .getPackageManager().getPackageInfo(getPackageName(), 0);
//  Config.localVersion = packageInfo.versionCode;
/
/  Config.serverVersion = 1;// 假定服务器版本为2,本地版本默认是1
//  } catch (NameNotFoundException e) {
//  e.printStackTrace();
//  }
initGlobal();
}
public void initGlobal() {
try {
Config.localVersion = getPackageManager().getPackageInfo(
getPackageName(), 0).versionCode; // 设置本地版本号
Config.serverVersion = 2;// 假定服务器版本为2,本地版本默认是1--实际开发中是从服务器获取最新版本号,android具体与后端的交互见我另///外的博⽂  } catch (Exception ex) {
ex.printStackTrace();
}
}
}
3.创建配置⽂件类Config.java,在这个类⾥⾯定义⼀些与版本相关的常量
fig;
public class Config {
//版本信息
public static int localVersion = 0;
public static int serverVersion = 0;
/* 下载包安装路径 */
public static final String savePath = "/sdcard/test/";
public static final String saveFileName = savePath + "test.apk";
}
4.编写更新服务类UpdateServcie.java
st.update;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.HttpURLConnection;
import java.URL;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
t.Intent;
import android.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;
fig.Config;
public class UpdateService extends Service {
// 标题
private int titleId = 0;
// ⽂件存储
private File updateDir = null;
private File updateFile = null;
// 下载状态
private final static int DOWNLOAD_COMPLETE = 0;
private final static int DOWNLOAD_FAIL = 1;
// 通知栏
private NotificationManager updateNotificationManager = null;
private Notification updateNotification = null;
// 通知栏跳转Intent
private Intent updateIntent = null;
private PendingIntent updatePendingIntent = null;
/***
* 创建通知栏
*/
RemoteViews contentView;
// 这样的下载代码很多,我就不做过多的说明
int downloadCount = 0;
int currentSize = 0;
long totalSize = 0;
int updateTotalSize = 0;
// 在onStartCommand()⽅法中准备相关的下载⼯作:
@SuppressWarnings("deprecation")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 获取传值
titleId = IntExtra("titleId", 0);
// 创建⽂件
if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment
.
getExternalStorageState())) {
updateDir = new ExternalStorageDirectory(),
Config.saveFileName);
updateFile = new Path(), getResources()
.getString(titleId) + ".apk");
}
this.updateNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);  this.updateNotification = new Notification();
// 设置下载过程中,点击通知栏,回到主界⾯
updateIntent = new Intent(this, UpdateActivity.class);
updatePendingIntent = Activity(this, 0, updateIntent,
0);
// 设置通知栏显⽰内容
updateNotification.icon = R.drawable.ic_launcher;
updateNotification.tickerText = "开始下载";
updateNotification.setLatestEventInfo(this, "QQ", "0%",
updatePendingIntent);
// 发出通知
// 开启⼀个新的线程下载,如果使⽤Service同步下载,会导致ANR问题,Service本⾝也会阻塞
new Thread(new updateRunnable()).start();// 这个是下载的重点,是下载的过程
StartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@SuppressLint("HandlerLeak")
private Handler updateHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DOWNLOAD_COMPLETE:
/
/ 点击安装PendingIntent
Uri uri = Uri.fromFile(updateFile);
Intent installIntent = new Intent(Intent.ACTION_VIEW);
installIntent.setDataAndType(uri,
"application/vnd.android.package-archive");
updatePendingIntent = Activity(
UpdateService.this, 0, installIntent, 0);
updateNotification.defaults = Notification.DEFAULT_SOUND;// 铃声提醒
updateNotification.setLatestEventInfo(UpdateService.this,
"QQ", "下载完成,点击安装。", updatePendingIntent);
/
/ 停⽌服务
stopService(updateIntent);
case DOWNLOAD_FAIL:
// 下载失败
updateNotification.setLatestEventInfo(UpdateService.this,
"QQ", "下载完成,点击安装。", updatePendingIntent);
default:
stopService(updateIntent);
}
}
};
public long downloadUpdateFile(String downloadUrl, File saveFile)    throws Exception {
HttpURLConnection httpConnection = null;
InputStream is = null;
FileOutputStream fos = null;
try {
URL url = new URL(downloadUrl);
httpConnection = (HttpURLConnection) url.openConnection();
httpConnection
.setRequestProperty("User-Agent", "PacificHttpClient");
if (currentSize > 0) {
httpConnection.setRequestProperty("RANGE", "bytes="
+ currentSize + "-");
}
httpConnection.setConnectTimeout(10000);
httpConnection.setReadTimeout(20000);
updateTotalSize = ContentLength();
if (ResponseCode() == 404) {
throw new Exception("fail!");
}
is = InputStream();
fos = new FileOutputStream(saveFile, false);
byte buffer[] = new byte[4096];
int readsize = 0;
while ((readsize = is.read(buffer)) > 0) {
fos.write(buffer, 0, readsize);
totalSize += readsize;
// 为了防⽌频繁的通知导致应⽤吃紧,百分⽐增加10才通知⼀次
if ((downloadCount == 0)
|| (int) (totalSize * 100 / updateTotalSize) - 10 > downloadCount) {      downloadCount += 10;
updateNotification.setLatestEventInfo(UpdateService.this,
"正在下载", (int) totalSize * 100 / updateTotalSize
+ "%", updatePendingIntent);
/
***
* 在这⾥我们⽤⾃定的view来显⽰Notification
*/
getPackageName(), ification_item);
ificationTitle, "正在下载");
ificationProgress, 100, downloadCount, false);
}
}
} finally {
if (httpConnection != null) {
httpConnection.disconnect();
}
if (is != null) {
is.close();
}
if (fos != null) {
fos.close();
}
}
return totalSize;
}
class updateRunnable implements Runnable {
Message message = updateHandler.obtainMessage();
public void run() {
message.what = DOWNLOAD_COMPLETE;
try {
// 增加权限<USES-PERMISSION
// android:name="android.permission.WRITE_EXTERNAL_STORAGE">;
if (!ists()) {
updateDir.mkdirs();
}
if (!ists()) {
}
// 下载函数,以QQ为例⼦
// 增加权限<USES-PERMISSION
// android:name="android.permission.INTERNET">;
long downloadSize = downloadUpdateFile(
"softfile.3g.qq:8080/msoft/179/1105/10753/MobileQQ1.0(Android)_Build0198.apk",      updateFile);
if (downloadSize > 0) {
// 下载成功
updateHandler.sendMessage(message);
}
} catch (Exception ex) {
ex.printStackTrace();
message.what = DOWNLOAD_FAIL;
// 下载失败
updateHandler.sendMessage(message);
}
}
}
}
5.编写活动类UpdateActivity
st.update;
fig.Config;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.app.AlertDialog;
t.DialogInterface;
t.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
public class UpdateActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
checkVersion();
}
/**
* 检查更新版本
*/
public void checkVersion() {
if (Config.localVersion < Config.serverVersion) {
Log.i("hgncxzy", "==============================");
// 发现新版本,提⽰⽤户更新
AlertDialog.Builder alert = new AlertDialog.Builder(this);

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。