Android版本檢測更新是每個應用升級所不可少的,以前早就做過一些,一直沒有時間與大家分享,現在就跟大家來分享一下我做的版本檢測更新吧。先上圖
點擊更新之后的
可能有人會問為啥點擊更新提示框不消失啊,可以根據自己的情況而定,有的需要強制更新,也是為了方便用戶看到下載的進度。我這里只是為了測試一下效果而已。真正的是點擊更新以后會在通知欄里面進行顯示的 效果就是這樣的
也有的可能需要在桌面上面展示給用戶,下面的效果
這些都是是需求而定的。不多說了上代碼
package com.liuyongxiang.update.activity;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONException;
import org.json.JSONObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.liuyongxiang.update.R;
import com.liuyongxiang.update.bean.VersionBean;
import com.liuyongxiang.update.utils.MyConstants;
import com.liuyongxiang.update.utils.SpTools;
import com.liuyongxiang.update.view.NumberProgressBar;
import com.liuyongxiang.update.view.OnProgressBarListener;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.PixelFormat;
import android.graphics.pdf.PdfDocument;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class SplashActivity extends Activity implements OnProgressBarListener {private static final int LOADMAIN =
1;
private static final int SHOWUPDATEDIALOG =
2;
protected static final int ERROR =
3;
private RelativeLayout rl_root;
private int versionCode;
private String versionName;
private TextView tv_versionName;
private VersionBean parseJson;
private long startTimeMillis;
private NumberProgressBar pb_download;
private Notification.Builder mBuilder;
private NotificationManager mNotificationManager;
public static final int NOTIFICATION_ID =
200;
public static final int MUTE =
0;
public static final int VIBRATE =
1;
public static final int SOUND =
2;
@Overrideprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);initView();initData();showUpdateDialog();}
/*** 耗時的功能封裝,只要耗時的處理,都放到此方法*/private void timeInitialization() {
if (SpTools.getBoolean(getApplicationContext(), MyConstants.AUTOUPDATE,
false)) {checkVerion();}}
private void initData() {PackageManager pm = getPackageManager();
try {PackageInfo packageInfo = pm.getPackageInfo(getPackageName(),
0);versionCode = packageInfo.versionCode;versionName = packageInfo.versionName;tv_versionName.setText(versionName);}
catch (NameNotFoundException e) {}}
private void checkVerion() {
new Thread(
new Runnable() {
@Overridepublic void run() {BufferedReader bfr =
null;HttpURLConnection conn =
null;
int errorCode = -
1;
try {startTimeMillis = System.currentTimeMillis();URL url =
new URL(
"http://10.0.2.2:8080/guardversion.json");conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(
5000);conn.setConnectTimeout(
5000);
int code = conn.getResponseCode();
if (code ==
200) {InputStream is = conn.getInputStream();bfr =
new BufferedReader(
new InputStreamReader(is));String line = bfr.readLine();StringBuilder json =
new StringBuilder();
while (line !=
null) {json.append(line);line = bfr.readLine();}parseJson = parseJson(json);}
else {errorCode =
404;}}
catch (MalformedURLException e) {errorCode =
4002;e.printStackTrace();}
catch (IOException e) {errorCode =
4001;e.printStackTrace();}
catch (JSONException e) {errorCode =
4003;e.printStackTrace();}
finally {Message msg = Message.obtain();
if (errorCode == -
1) {msg.what = isNewVersion(parseJson);}
else {msg.what = ERROR;msg.arg1 = errorCode;}
long endTime = System.currentTimeMillis();
if (endTime - startTimeMillis <
3000) {SystemClock.sleep(
3000 - (endTime - startTimeMillis));}handler.sendMessage(msg);
try {
if (bfr !=
null) {bfr.close();}
if (conn !=
null) {conn.disconnect();}}
catch (IOException e) {e.printStackTrace();}}}}).start();}
private Handler handler =
new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case LOADMAIN:loadMain();
break;
case ERROR:
switch (msg.arg1) {
case 404:Toast.makeText(getApplicationContext(),
"404資源找不到",
0).show();
break;
case 4001:Toast.makeText(getApplicationContext(),
"4001沒有網絡",
0).show();
break;
case 4003:Toast.makeText(getApplicationContext(),
"4003json格式錯誤",
0).show();
break;
default:
break;}loadMain();
break;
case SHOWUPDATEDIALOG:showUpdateDialog();
break;
default:
break;}}};
private AlertDialog dialog;
private void loadMain() {Intent intent =
new Intent(SplashActivity.
this, MainActivity.class);startActivity(intent);finish();};
protected int isNewVersion(VersionBean parseJson) {
int serverCode =
2;System.out.println(
"serverCode----->" + serverCode);
if (serverCode == versionCode) {
return LOADMAIN;}
else {
return SHOWUPDATEDIALOG;}}
/*** 顯示是否更新新版本的對話框*/public void showUpdateDialog() {dialog =
new AlertDialog.Builder(
this).create();dialog.setCancelable(
false);dialog.show();Window window = dialog.getWindow();window.setContentView(R.layout.prompt_alertdialog);LinearLayout ll_title = (LinearLayout) window.findViewById(R.id.ll_title);ll_title.setVisibility(View.VISIBLE);TextView tv_title = (TextView) window.findViewById(R.id.tv_title);pb_download = (NumberProgressBar) window.findViewById(R.id.pb_splash_download);pb_download.setVisibility(View.GONE);pb_download.setOnProgressBarListener(
this);tv_title.setText(
"版本更新");TextView tv_content = (TextView) window.findViewById(R.id.tv_content);tv_content.setMovementMethod(
new ScrollingMovementMethod());tv_content.setText(
"是否更新新版本?新版本的具有如下特性:1.是否更新新版本?新版本的具有如下特性 2.是否更新新版本?新版本的具有如下特性 3.是否更新新版本?新版本的具有如下特性 4.是否更新新版本?新版本的具有如下特性 5.是否更新新版本?新版本的具有如下特性 6.是否更新新版本?新版本的具有如下特性 7.是否更新新版本?新版本的具有如下特性 8.是否更新新版本?新版本的具有如下特性");
final TextView tv_sure = (TextView) window.findViewById(R.id.tv_sure);
final TextView tv_cancle = (TextView) window.findViewById(R.id.tv_cancle);tv_cancle.setText(
"取消");tv_cancle.setOnClickListener(
new View.OnClickListener() {
@Overridepublic void onClick(View arg0) {loadMain();dialog.cancel();}});tv_sure.setText(
"更新");tv_sure.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {downLoadNewApk();createFloatView();tv_cancle.setEnabled(
false);tv_sure.setEnabled(
false);dialog.cancel();loadMain();pb_download.setVisibility(View.VISIBLE);}});}
/*** 新版本的下載安裝*/protected void downLoadNewApk() {HttpUtils utils =
new HttpUtils();File file =
new File(
"/mnt/sdcard/測試.apk");file.delete();utils.download(
"http://www.gamept.cn/d/file/game/qipai/20140627/HappyLordZZ_1.0.19_20140325_300002877528_2200139763.apk",
"/mnt/sdcard/測試.apk",
new RequestCallBack<File>() {
@Overridepublic void onLoading(
final long total,
final long current,
boolean isUploading) {pb_download.setVisibility(View.VISIBLE);
int max = (
int) total;
int progress = (
int) current;pb_download.setMax(max);pb_download.setProgress(progress);pb_download2.setMax(max);pb_download2.setProgress(progress);showNotifi(max, progress);
super.onLoading(total, current, isUploading);}
@Overridepublic void onSuccess(ResponseInfo<File> arg0) {Toast.makeText(getApplicationContext(),
"下載新版本成功",
1).show();installApk();pb_download.setVisibility(View.GONE);rl_notification.setVisibility(View.GONE);}
@Overridepublic void onFailure(HttpException arg0, String arg1) {Toast.makeText(getApplicationContext(),
"下載新版本失敗",
1).show();pb_download.setVisibility(View.GONE);}});}
private NumberProgressBar pb_download2;
private RelativeLayout rl_notification;
/*** 安裝下載的新版本*/protected void installApk() {Intent intent =
new Intent(
"android.intent.action.VIEW");intent.addCategory(
"android.intent.category.DEFAULT");String type =
"application/vnd.android.package-archive";Uri data = Uri.fromFile(
new File(
"/mnt/sdcard/測試.apk"));intent.setDataAndType(data, type);startActivityForResult(intent,
0);}
@Overrideprotected void onActivityResult(
int requestCode,
int resultCode, Intent data) {loadMain();
super.onActivityResult(requestCode, resultCode, data);}
/*** @param jsonString* url的json數據* @return url信息封裝對象* @throws JSONException*/protected VersionBean
parseJson(StringBuilder jsonString)
throws JSONException {VersionBean bean =
new VersionBean();JSONObject jsonObj;jsonObj =
new JSONObject(jsonString +
"");
int versionCode = jsonObj.getInt(
"version");String url = jsonObj.getString(
"url");String desc = jsonObj.getString(
"desc");bean.setDesc(desc);bean.setUrl(url);bean.setVersionCode(versionCode);
return bean;}
/*** 初始化界面*/private void initView() {setContentView(R.layout.activity_main);rl_root = (RelativeLayout) findViewById(R.id.rl_splash_root);tv_versionName = (TextView) findViewById(R.id.tv_splash_version_name);}
@Overridepublic void onProgressChange(
int current,
int max) {pb_download.setProgress(current);pb_download2.setProgress(current);}
private void createFloatView() {
final WindowManager.LayoutParams wmParams =
new WindowManager.LayoutParams();getApplication();
final WindowManager mWindowManager = (WindowManager) getApplication().getSystemService(Context.WINDOW_SERVICE);wmParams.type = LayoutParams.TYPE_PHONE;wmParams.format = PixelFormat.RGBA_8888;wmParams.flags = LayoutParams.FLAG_NOT_FOCUSABLE;wmParams.gravity = Gravity.LEFT | Gravity.TOP;wmParams.x =
0;wmParams.y =
0;wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;LayoutInflater inflater = LayoutInflater.from(getApplication());
final View mFloatLayout = inflater.inflate(R.layout.activity_notification,
null);mWindowManager.addView(mFloatLayout, wmParams);rl_notification = (RelativeLayout) mFloatLayout.findViewById(R.id.rl_notification);pb_download2 = (NumberProgressBar) mFloatLayout.findViewById(R.id.pb_download);mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(
0,View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(
0, View.MeasureSpec.UNSPECIFIED));rl_notification.setOnTouchListener(
new OnTouchListener() {
@Overridepublic boolean onTouch(View v, MotionEvent event) {wmParams.x = (
int) event.getRawX()- rl_notification.getMeasuredWidth() /
2;wmParams.y = (
int) event.getRawY()- rl_notification.getMeasuredHeight() /
2 -
25;mWindowManager.updateViewLayout(mFloatLayout, wmParams);
return false;}});}
private void showNotification(
final int total,
final int current) {mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);mBuilder =
new Notification.Builder(SplashActivity.
this);LayoutInflater inflater = LayoutInflater.from(getApplication());View view = inflater.inflate(R.layout.activity_notification,
null);mBuilder.setContentTitle(
"這是測試").setContentText(
"下載中...").setSmallIcon(R.drawable.app_icon);
new Thread(
new Runnable() {
@SuppressLint(
"NewApi")
@Overridepublic void run() {mBuilder.setProgress(total, current,
false);mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
if (current / total ==
1) {mNotificationManager.cancel(
0);}}}).start();}
private void showNotifi(
final int total,
final int current) {NotificationManager notiManage;Notification note;mBuilder =
new Notification.Builder(SplashActivity.
this);notiManage = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);note =
new Notification();note.flags = Notification.FLAG_AUTO_CANCEL;RemoteViews contentView =
new RemoteViews(getPackageName(),R.layout.activity_notifi);contentView.setTextViewText(R.id.notificationTitle,
"這是測試");String str_progress =current*
100/total+
"%"; contentView.setTextViewText(R.id.notificationPercent, str_progress);contentView.setProgressBar(R.id.notificationProgress, total, current,
false);note.contentView = contentView;note.tickerText =
"正在下載";note.icon = R.drawable.app_icon;PendingIntent p = PendingIntent.getActivity(SplashActivity.
this,
0,
new Intent(Intent.ACTION_VIEW),
0);note.contentIntent = p;notiManage.notify(NOTIFICATION_ID, note);
if (current / total ==
1) {notiManage.cancelAll();}}
}
這只是一些簡單的代碼,如果想測試一下具體效果
點擊免費下載源碼
如果有問題請加Android交流群 470707794或留言
總結
以上是生活随笔為你收集整理的Android 版本检测更新的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。