最近听说友盟的自动更新后期会不让用了,所以自己谢了一个带有进度条通知栏的检查更新,请大家多提意见,话不多说,上代码。
首先,要去后台获取检查的接口判断是否要更新,如果需要更新,如下;
String ver;//该参数为最新的版本号
String url;//最新apk的文件地址
String notes;//要显示的更新日志
UpdateManager manager = new UpdateManager(ver, url, notes, EasyHomeworkActivity.this);
// 检查软件更新
manager.checkUpdate();
第二步,弹出检查更新对话框选择更新并在通知栏显示进度
UpdateManager类基本就是封装好的一个完善的更新类
package com.easyhomework.more.data;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.Toast;
import com.easyhomework.R;
import com.easyhomework.context.EasyHomeworkActivity;
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;
/**
* 作者:lff
* 时间;2016-4-11 14:38
* 描述:检查更新
*/
public class UpdateManager {
/* 下载中 */
private static final int DOWNLOAD = 1;
/* 下载结束 */
private static final int DOWNLOAD_FINISH = 2;
//判断是否更新中
public static String tag = "1";//未点击更新
/* 下载保存路径 */
private String mSavePath;
/* 记录进度条数量 */
private int progress;
/* 是否取消更新 */
private boolean cancelUpdate = false;
private String ver;//版本号
private String urlapk;//apk地址
private String notes;//升级说明
private Context mContext;
private int len;
private NotificationManager manager;
private Notification notif;
/* 更新进度条 */
private ProgressBar mProgress;
private Dialog mDownloadDialog;
// RemoteViews contentView;
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
// 正在下载
case DOWNLOAD:
// 设置进度条位置
mProgress.setProgress(progress);
progress, false);
notif.contentView.setTextViewText(R.id.content_view_text1, "正在下载... "+progress+"%");
notif.contentView.setProgressBar(R.id.content_view_progress, 100, progress, false);
manager.notify(0, notif);
break;
case DOWNLOAD_FINISH:
// 安装文件
notif.contentView.setTextViewText(R.id.content_view_text1, "下载完成!");
notif.contentView.setProgressBar(R.id.content_view_progress, 100, 100, false);
manager.notify(0, notif);
tag = "2";//更新完成开始安装
installApk();
break;
default:
break;
}
}
;
};
public UpdateManager(String ver, String url, String notes, Context context) {
this.mContext = context;
this.ver = ver;
this.urlapk = url;
this.notes = notes;
}
public boolean isShowToast = true;
/**
* 检测软件更新
*/
public void checkUpdate() {
if (isUpdate()) {
// 显示提示对话框
if(tag.equals("1")){
showNoticeDialog();
}else{
}
} else {
if(isShowToast){
Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show();
}
}
}
/**
* 检查软件是否有更新版本
*
* @return
*/
private boolean isUpdate() {
// 获取当前软件版本
int versionCode = getVersionCode(mContext);
int serviceCode = Integer.valueOf(ver);
// 版本判断
if (serviceCode > versionCode) {
return true;
}
return false;
}
/**
* 获取软件版本号
*
* @param context
* @return
*/
private int getVersionCode(Context context) {
int versionCode = 0;
try {
// 获取软件版本号,对应AndroidManifest.xml下android:versionCode
versionCode = context.getPackageManager().getPackageInfo("com.easyhomework", 0).versionCode;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
return versionCode;
}
/**
* 显示软件更新对话框
*/
private void showNoticeDialog() {
// 构造对话框
Builder builder = new Builder(mContext);
builder.setTitle(R.string.soft_update_title);
builder.setMessage(notes);
// 更新
builder.setPositiveButton(R.string.soft_update_updatebtn, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// if (tag) {
Toast.makeText(mContext, "后台更新中,请稍后...", Toast.LENGTH_LONG).show();
tag="3";//开始更新
// } else {
// // 显示下载对话框
showDownloadDialog();
// Toast.makeText(mContext, "后台下载更新中...", Toast.LENGTH_LONG).show();
// }
}
});
// 稍后更新
builder.setNegativeButton(R.string.soft_update_later, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog noticeDialog = builder.create();
noticeDialog.show();
}
/**
* 显示软件下载对话框
*/
private void showDownloadDialog() {
// 构造软件下载对话框
Builder builder = new Builder(mContext);
builder.setTitle(R.string.soft_updating);
// 给下载对话框增加进度条
final LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.softupdate_progress, null);
mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
builder.setView(v);
// 取消更新
builder.setNegativeButton(R.string.soft_update_cancel, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// 设置取消状态
cancelUpdate = true;
}
});
mDownloadDialog = builder.create();
// mDownloadDialog.show(); //不让下载进度条显示
//点击通知栏后打开的activity
Intent intent = new Intent(mContext,EasyHomeworkActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
manager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
notif = new Notification();
notif.icon = R.drawable.app_icon;
notif.tickerText = "更新通知";
//通知栏显示所用到的布局文件
notif.contentView = new RemoteViews(mContext.getPackageName(), R.layout.p);
notif.contentIntent = pIntent;
manager.notify(0, notif);
// 下载文件
downloadApk();
}
/**
* 下载apk文件
*/
private void downloadApk() {
// 启动新线程下载软件
new downloadApkThread().start();
}
int downloadCount = 0;
/**
* 下载文件线程
*
* @author coolszy
* @date 2012-4-26
* @blog http://blog.92coding.com
*/
private class downloadApkThread extends Thread {
@Override
public void run() {
try {
// 判断SD卡是否存在,并且是否具有读写权限
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// 获得存储卡的路径
String sdpath = Environment.getExternalStorageDirectory() + "/";
mSavePath = sdpath + "download";
URL url = new URL(urlapk);
// 创建连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
// 获取文件大小
int length = conn.getContentLength();
// 创建输入流
InputStream is = conn.getInputStream();
File file = new File(mSavePath);
// 判断文件目录是否存在
if (!file.exists()) {
file.mkdir();
}
File apkFile = new File(mSavePath, "easy.apk");
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);
Log.i("progress","progress==="+progress);
Log.i("progress","count==="+count+numread);
// 更新进度
//为了防止频繁的通知导致应用吃紧,百分比增加10才通知一次
if(downloadCount == 0 || progress-5>downloadCount){
downloadCount+=5;
mHandler.sendEmptyMessage(DOWNLOAD);
}
if (numread <= 0) {
// 下载完成
mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
break;
}
// 写入文件
fos.write(buf, 0, numread);
} while (!cancelUpdate);// 点击取消就停止下载.
fos.close();
is.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
;
/**
* 安装APK文件
*/
private void installApk() {
File apkfile = new File(mSavePath, "easy.apk");
if (!apkfile.exists()) {
return;
}
// 通过Intent安装APK文件
;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
mContext.startActivity(intent);
}
}
还有一个是通知栏的布局
通知栏布局 p
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#00000000"
android:orientation="vertical"
android:padding="7dp"
>
<ImageView
android:id="@+id/content_view_image"
android:layout_width="25dp"
android:layout_height="25dp"
android:src="@drawable/app_icon"
/>
<TextView
android:id="@+id/content_view_text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0%"
android:textColor="#969191"
android:layout_toRightOf="@id/content_view_image"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:layout_marginLeft="15dp"
/>
<ProgressBar
android:id="@+id/content_view_progress"
android:layout_width="fill_parent"
android:layout_height="6dp"
style="@android:style/Widget.ProgressBar.Horizontal"
android:max="100"
android:layout_below="@id/content_view_image"
android:layout_marginTop="7dp"
android:progressDrawable="@drawable/progressbar_color"
/>
RelativeLayout>
大家仔细看UpdateManager 注释,很简单的,最近比较忙,这个博客有点粗糙,有什么问题可以加我QQ群大家一起探讨一下。