Android 檢查更新版本(帶有通知欄,進度條,Notification)
阿新 • • 發佈:2019-01-29
最近聽說友盟的自動更新後期會不讓用了,所以自己謝了一個帶有進度條通知欄的檢查更新,請大家多提意見,話不多說,上程式碼。
首先,要去後臺獲取檢查的介面判斷是否要更新,如果需要更新,如下;
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
<?xml version="1.0" encoding="utf-8"?>
<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群大家一起探討一下。