版本更新
需求是每次登进主页面都提交一次版本名到服务器,由服务器判断是否应该更新,如果需要更新会返回true并返回需要更新所用到的json数据(更新内容,新版本名称等),如果不用就会返回false。
//检查版本更新,这里用得是Xutils提交数据请求服务器回调 public static void checkVersionUpdate(String versionName) { final String checkVersionUrl = UPDATE_URL + "token=" + "2b5c2d36fc41358c299f9230d8a15e501b45f1b473c0cbacb54afa7bdc03e800&" + "app_id=3&" + "os_type=android&" + "version=" + versionName; RequestParams requestParams = new RequestParams(checkVersionUrl); x.http().get(requestParams, new Callback.CommonCallback<String>() { @Override public void onSuccess(String result) { rver = new RequestVersion(result); //这里写了一个工具类来解析服务器返回的json数据 Log.i("调回来的信息",result); if (rver.getRv()==200){ if (rver.isUpd()){ updateContent = rver.getChange();//获取更新的内容 //文件路径 apkPath = ROOT_URL + rver.getPath();//获取APK文件的服务器路径 //如果返回真,则要更新 instance.updateMessage(IUpdateListener.UpdateStatus.YES,"YES"); }else{ //当前版本为最新,不用更新 instance.updateMessage(IUpdateListener.UpdateStatus.NO,"NO"); } }else { Log.i("出错了,传回来的信息", rver.getMsg()); } } @Override public void onError(Throwable ex, boolean isOnCallback) { System.out.println("发送验证消息的时候发生了错误"); } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { } }); }
public void updateMessage(IUpdateListener.UpdateStatus status, String message) { this.updateStatus = status; if (this.updateListener != null) this.updateListener.onUpdate(status, message); }
解析的工具类
/** * @author Admin * @version $Rev$ * @des ${TODO} * @updateAuthor $Author$ * @updateDes ${TODO} * * 这里有用的是阿里巴巴解析json用的工具,在配置里面加两句话就行啦 * compile 'com.alibaba:fastjson:1.2.37' compile 'com.alibaba:fastjson:1.1.62.android' */ public class RequestVersion { public static final String RETURN_VAL = "rv"; public static final String MESSAGE = "msg"; public static final String UPDATE = "upd"; public static final String PATH = "path"; public static final String VERSION = "version"; public static final String DATA = "data"; public static final String PUBLISH_DATE = "publish_date"; public static final String CHAGNGELOG = "changelog"; private String version; private String path; private String msg; private String pubDate; private String change; private int rv; private boolean upd; // {"data":{"publish_date":"2017-09-27", // "changelog":"【新增】全新的设计,更好的体验,页面美化,酷炫动态效果,美美哒\n【优化】客户端和H5的问题\n【修复】修复了若干BUG\n【新增】全新的设计,更好的体验\n【优化】客户端和H5的问题\n【修复】修复了若干BUG\n【新增】全新的设计,更好的体验\n【优化】客户端和H5的问题\n【修复】修复了若干BUG\n【新增】全新的设计,更好的体验\n【优化】客户端和H5的问题\n【修复】修复了若干BUG\n【新增】全新的设计,更好的体验\n【优化】客户端和H5的问题\n【修复】修复了若干BUG\n【新增】全新的设计,更好的体验\n【优化】客户端和H5的问题\n【修复】修复了若干BUG\n【新增】全新的设计,更好的体验\n【优化】客户端和H5的问题\n【修复】修复了若干BUG\n【新增】全新的设计,更好的体验\n【优化】客户端和H5的问题\n【修复】修复了若干BUG\n【新增】全新的设计,更好的体验\n【优化】客户端和H5的问题\n【修复】修复了若干BUG", // "path":"/static/downloads/android/sf.apk", // "app_id":3, // "os_type":"android", // "size":14969839, // "version":"1.0.1"}, // "rv":200, // "upd":true, // "msg":"当前版本不是最新版本,建议更新.", // "filter":{"app_id":"3", // "os_type":"android", // "version":"1.0"}} public RequestVersion(String result) { JSONObject res = JSON.parseObject(result); Log.i("服务器回调的信息", String.valueOf(res)); //回调码和回调信息 this.rv = res.getInteger(RETURN_VAL); this.msg = res.getString(MESSAGE); this.upd = res.getBoolean(UPDATE); if (rv==200){ //文件的路径 if (res.containsKey(DATA)){ this.path = res.getJSONObject(DATA).getString(PATH); Log.i("解析出来的文件路径",path); } //上传的时间 if (res.containsKey(PUBLISH_DATE)){ this.pubDate = res.getString(PUBLISH_DATE); } //版本号 if (res.containsKey(DATA)){ this.version = res.getJSONObject(DATA).getString(VERSION); Log.i("解析出来的版本号",version); } //更新内容 if (res.containsKey(DATA)){ this.change = res.getJSONObject(DATA).getString(CHAGNGELOG); Log.i("解析出来的更新内容",change); } } } public String getChange() { return change; } public String getVersion() { return version; } public String getPath() { return path; } public String getMsg() { return msg; } public String getPubDate() { return pubDate; } public int getRv() { return rv; } public boolean isUpd() { return upd; } }
解析完数据就知道该不该更新了
这种时候可以设置一个更新的状态
方便我们确定在什么状态的时候做什么事情
/** * @author Admin * @version $Rev$ * @des ${TODO} * @updateAuthor $Author$ * @updateDes ${TODO} * 更新的状态监听 */ public interface IUpdateListener { public enum UpdateStatus { YES, //要更新 NO, //不用更新 NOUPDATE, //文件存不存在 NOINTERNET, //没有网络连接 ERROR, //检测失败 UPDATEING //正在更新 } //抽象更新状态 abstract void onUpdate(UpdateStatus status, String message); }
这样只要继承一下这个接口或者写个实现类就可以获取到更新的状态
将获取到的状态发送到消息队列
队列收到什么状态就会做什么事情
Runnable runnable = new Runnable() { @Override public synchronized void run() { Log.i("全局变量过来的更新状态", String.valueOf(Common.getUpdateStatus())); mUpdate.onUpdate(Common.getUpdateStatus(), "空"); handler.postDelayed(this, 1000); } };
Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.arg1) { case 1://成功 //弹出更新对话框 showPopupWindow(); handler.removeCallbacks(runnable); break; case 0://失败 if (3 > isUpdate) { handler.postDelayed(runnable, 1000); System.out.println(isUpdate); isUpdate++; } else { handler.removeCallbacks(runnable); } break; case 2://没有网络连接 handler.removeCallbacks(runnable); break; case 3://检测失败 handler.removeCallbacks(runnable); break; case 4://文件已存在 handler.removeCallbacks(runnable); break; case 5://正在更新 Common.installApk(MainActivity.this,popupWindow,mProgressBar); break; default: break; } } };
如果要更新的话那就弹出一个对话框
/** * 更新内容界面 */ private void showPopupWindow() { View contentView = basePopupwindow(id.rvMainFunc, R.layout.update_pop); //更新内容滑动 TextView lvUpdateCont = (TextView) contentView.findViewById(id.lvUpdateCont); lvUpdateCont.setMovementMethod(ScrollingMovementMethod.getInstance()); lvUpdateCont.setText(Common.getUpdateContent()); //点击OX不更新 ImageView ivcirleX = (ImageView) contentView.findViewById(id.ivcirleX); ivcirleX.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (popupWindow != null && popupWindow.isShowing()) { popupWindow.dismiss(); popupWindow = null; } } }); //立即更新 ImageView btUpdate = (ImageView) contentView.findViewById(id.btUpdate); btUpdate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (popupWindow != null && popupWindow.isShowing()) { popupWindow.dismiss(); popupWindow = null; showPopupWindowUpdate(); } } }); } private View basePopupwindow(int parentlayout, int contlayout) { //设置窗口的形状 Rect frame = new Rect(); //先拿到窗口,然后拿到装饰的视图,然后拿到可以显示的形状 getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); //设置布局 View parentView = (View) this.findViewById(parentlayout); View contentView = LayoutInflater.from(this).inflate(contlayout, null); popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true); popupWindow.setAnimationStyle(android.R.style.Animation_Dialog); //设置一个动画。 //背景虚化 WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 0.4f; getWindow().setAttributes(lp); contentView.setFocusable(true); contentView.setFocusableInTouchMode(true); ColorDrawable cd = new ColorDrawable(0x000000); popupWindow.setBackgroundDrawable(cd); popupWindow.setOutsideTouchable(false); //点击外部关闭。 popupWindow.showAtLocation(parentView, Gravity.CENTER, 0, 0); popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { //在dismiss中恢复透明度 public void onDismiss() { WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.alpha = 1f; getWindow().setAttributes(lp); } }); return contentView; }
用的是popupwindow,这里就不多说
如果确认要更新,得弹出更新的进度条以及去服务器拿到下载的文件
/** * 显示下载的界面 */ private void showPopupWindowUpdate() { View contentView = basePopupwindow(id.rvMainFunc, R.layout.updating_pop); mProgressBar = (HorizontalProgressBarWithNumber) contentView.findViewById(R.id.hpbProgressUpdate); //取消 Button cancle = (Button) contentView.findViewById(R.id.btupdatecancle); cancle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Common.cancelDownload(); popupWindow.dismiss(); } }); //后台下载 Button back = (Button) contentView.findViewById(R.id.btBack); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(MainActivity.this,"暂时不支持后台下载", Toast.LENGTH_SHORT).show(); } }); //去服务器获取文件 mUpdate.onUpdate(UPDATEING, "UPDATEING"); }
这里发完消息到队列里,在队列里有个
Common.installApk(MainActivity.this,popupWindow,mProgressBar);
方法去请求服务器的文件
/** * 安装apk * * @param */ public static void installApk(final Context context, final PopupWindow popupWindow, final HorizontalProgressBarWithNumber mProgressBar) { System.out.println(getApkPath()); RequestParams requestParams = new RequestParams(getApkPath()); final String filePath = getSystemFilePath(context) + "/sf.apk"; // /data/data/com.foxconn.ackh.cd.sf/files /static/downloads/android/sf.apk Log.i("文件保存路径", filePath); requestParams.setSaveFilePath(filePath); cancelable = x.http().get(requestParams, new Callback.ProgressCallback<File>() { @Override public void onSuccess(File result) { Toast.makeText(context, "下载成功", Toast.LENGTH_SHORT).show(); popupWindow.dismiss(); System.out.println(result); RxAppUtils.InstallAPK(context, filePath); Common.exit(); } @Override public void onError(Throwable ex, boolean isOnCallback) { ex.printStackTrace(); Toast.makeText(context, "下载失败,请检查网络和SD卡", Toast.LENGTH_SHORT).show(); popupWindow.dismiss(); } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { } @Override public void onWaiting() { System.out.println("waiting"); } @Override public void onStarted() { System.out.println("start"); } @Override public void onLoading(long total, long current, boolean isDownloading) { mProgressBar.setMax((int) total); mProgressBar.setProgress((int) current); } }); }
这个还能获取文件的最大值和当前值,当前值/最大值就可以拿到当前下载进度的百分比
获取到成功之后就直接安装并退出当前APP,流程就结束了
进度条样式是自定义的,修改了网上找来的一个自定义进度条
package com.foxconn.ackh.cd.sf.entity; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.util.TypedValue; import android.widget.ProgressBar; import com.foxconn.ackh.cd.sf.R; public class HorizontalProgressBarWithNumber extends ProgressBar { private static final int DEFAULT_TEXT_SIZE = 10; //进度文字大小 private static final int DEFAULT_TEXT_COLOR = 0XFF1C7ECB; //加载完了的进度条的颜色 #1c7ecb private static final int DEFAULT_COLOR_UNREACHED_COLOR = 0xFFd3d6da; //还没有走到的进度条颜色 private static final int DEFAULT_HEIGHT_REACHED_PROGRESS_BAR = 4; //加载完了的进度条的粗细 private static final int DEFAULT_HEIGHT_UNREACHED_PROGRESS_BAR = 4; //没加载的进度条的粗细 private static final int DEFAULT_SIZE_TEXT_OFFSET = 1; //100%背后空白的大小 private Resources res = getResources(); //获取资源文件 private Bitmap plane= BitmapFactory.decodeResource(res, R.drawable.pic_update_balloon);//中间的小气球 /** * painter of all drawing things */ protected Paint mPaint = new Paint(); //画笔 /** * color of progress number */ protected int mTextColor = DEFAULT_TEXT_COLOR; //进度条数字颜色 /** * size of text (sp) */ protected int mTextSize = sp2px(DEFAULT_TEXT_SIZE); //进度条文字大小 /** * offset of draw progress */ protected int mTextOffset = dp2px(DEFAULT_SIZE_TEXT_OFFSET); //进度条文字背后的空白大小 /** * height of reached progress bar */ protected int mReachedProgressBarHeight = dp2px(DEFAULT_HEIGHT_REACHED_PROGRESS_BAR);//加载完了的进度条的粗细 /** * color of reached bar */ protected int mReachedBarColor = DEFAULT_TEXT_COLOR; //加载完了的进度条的粗细 /** * color of unreached bar */ protected int mUnReachedBarColor = DEFAULT_COLOR_UNREACHED_COLOR; //还没有走到的进度条颜色 /** * height of unreached progress bar */ protected int mUnReachedProgressBarHeight = dp2px(DEFAULT_HEIGHT_UNREACHED_PROGRESS_BAR);//没加载的进度条的粗细 /** * view width except padding */ protected int mRealWidth; protected boolean mIfDrawText = true; protected static final int VISIBLE = 0; public HorizontalProgressBarWithNumber(Context context, AttributeSet attrs) { this(context, attrs, 0); } public HorizontalProgressBarWithNumber(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); obtainStyledAttributes(attrs); mPaint.setTextSize(mTextSize); mPaint.setColor(mTextColor); } @Override protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = MeasureSpec.getSize(widthMeasureSpec);//画板的宽度 int height = measureHeight(heightMeasureSpec);//画板的高度 setMeasuredDimension(width, height/3); //设置画板大小 //这个没看懂 mRealWidth = getMeasuredWidth() - getPaddingRight() - getPaddingLeft(); } /** * 画板高度 * @param measureSpec * @return */ private int measureHeight(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { float textHeight = plane.getHeight();//plane.getHeight(); /*(mPaint.descent() - mPaint.ascent())+*/ result = (int) (getPaddingTop() + getPaddingBottom() + Math.max( Math.max(mReachedProgressBarHeight, mUnReachedProgressBarHeight), Math.abs(textHeight))); if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } /** * 拿到样式属性 * * @param attrs */ private void obtainStyledAttributes(AttributeSet attrs) { // init values from custom attributes final TypedArray attributes = getContext().obtainStyledAttributes( attrs, R.styleable.HorizontalProgressBarWithNumber); mTextColor = attributes .getColor( R.styleable.HorizontalProgressBarWithNumber_progress_text_color, DEFAULT_TEXT_COLOR); mTextSize = (int) attributes.getDimension( R.styleable.HorizontalProgressBarWithNumber_progress_text_size, mTextSize); mReachedBarColor = attributes .getColor( R.styleable.HorizontalProgressBarWithNumber_progress_reached_color, mTextColor); mUnReachedBarColor = attributes .getColor( R.styleable.HorizontalProgressBarWithNumber_progress_unreached_color, DEFAULT_COLOR_UNREACHED_COLOR); mReachedProgressBarHeight = (int) attributes .getDimension( R.styleable.HorizontalProgressBarWithNumber_progress_reached_bar_height, mReachedProgressBarHeight); mUnReachedProgressBarHeight = (int) attributes .getDimension( R.styleable.HorizontalProgressBarWithNumber_progress_unreached_bar_height, mUnReachedProgressBarHeight); mTextOffset = (int) attributes .getDimension( R.styleable.HorizontalProgressBarWithNumber_progress_text_offset, mTextOffset); int textVisible = attributes .getInt(R.styleable.HorizontalProgressBarWithNumber_progress_text_visibility, VISIBLE); if (textVisible != VISIBLE) { mIfDrawText = false; } attributes.recycle(); } @Override protected synchronized void onDraw(Canvas canvas) { canvas.save(); canvas.translate(getPaddingLeft(), getHeight() / 2); boolean noNeedBg = false; float radio = getProgress() * 0.7f / getMax(); float progressPosX = (int) (mRealWidth * radio); float pre = getProgress() * 100f / getMax(); String text = String.format("%3.1f%%",pre); // mPaint.getTextBounds(text, 0, text.length(), mTextBound); float planeWidth = plane.getWidth();// mPaint.measureText(text); float planeHeight = plane.getHeight(); //(mPaint.descent() + mPaint.ascent()) / 2; float textWidth = mPaint.measureText(text); float textHeight = (mPaint.descent() + mPaint.ascent()) / 2; if (progressPosX + planeWidth > mRealWidth) { progressPosX = mRealWidth - planeWidth; noNeedBg = true; } // draw reached bar float endX = progressPosX - mTextOffset / 2 ; if (endX > 0) { mPaint.setColor(mReachedBarColor); mPaint.setStrokeWidth(mReachedProgressBarHeight); canvas.drawLine(0, 0, endX, 0, mPaint); } // draw progress bar // measure text bound // draw unreached bar if (!noNeedBg) { //progressPosX 进度条戳进去的位置 float start = progressPosX-78 + mTextOffset / 2 + planeWidth; mPaint.setColor(mUnReachedBarColor); mPaint.setStrokeWidth(mUnReachedProgressBarHeight); canvas.drawLine(start, 0, mRealWidth-100, 0, mPaint); } if (mIfDrawText) { //mPaint.setColor(mTextColor); //canvas.drawText(text, progressPosX, -textHeight, mPaint); //-textHeight + 18气球高低位置 //progressPosX 进度条戳进去的位置 canvas.drawBitmap(plane,progressPosX-40,-planeHeight + 18,mPaint); mPaint.setColor(0XFF1C7ECB); mPaint.setTextSize(20); canvas.drawText(text, mRealWidth-60, -textHeight, mPaint); } canvas.restore(); } /** * dp 2 px * * @param dpVal */ protected int dp2px(int dpVal) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, getResources().getDisplayMetrics()); } /** * sp 2 px * * @param spVal * @return */ protected int sp2px(int spVal) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, getResources().getDisplayMetrics()); } }
弹出窗口的布局文件
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" > <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/rlFindNewVersion" style="@style/MyDialogStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#00000000" android:layout_alignParentLeft="false" android:layout_alignParentStart="false" android:layout_centerInParent="true" android:layout_centerVertical="true"> <!--<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/frame_1" android:layout_width="wrap_content" android:layout_height="wrap_content" >--> <RelativeLayout android:id="@+id/rlFindNewVersionIv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:layout_below="@+id/rlContent" android:layout_alignLeft="@+id/rlContent" android:layout_alignRight="@+id/rlContent"> <ImageView android:id="@+id/ivcirleX" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="false" android:layout_alignParentRight="false" android:layout_alignParentStart="false" android:layout_alignParentTop="false" android:layout_centerHorizontal="true" android:layout_centerInParent="false" android:layout_centerVertical="false" android:layout_marginTop="5dp" android:background="@drawable/bt_update_close_normal" android:clickable="true"/> </RelativeLayout> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/flFindNewVersionIv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginRight="80dp" android:layout_marginTop="50dp" android:background="@drawable/bg_update_normal"> <ImageView android:id="@+id/ivFindNewVersion" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical|center_horizontal" android:layout_marginTop="6dp" android:background="@drawable/pic_update_normal" android:padding="5dp"/> </FrameLayout> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_marginRight="54dp" android:background="@drawable/pic_update_balloon"> </FrameLayout> <!--</FrameLayout>--> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/rlContent" style="@style/MyDialogStyle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/flFindNewVersionIv" android:layout_alignRight="@+id/flFindNewVersionIv" android:layout_below="@+id/flFindNewVersionIv" android:background="#ffffff" android:orientation="vertical"> <TextView android:id="@+id/txtFileSize" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@+id/txtNewVersion" android:layout_marginTop="15dp" android:layout_marginLeft="5dp" android:textColor="#999999" android:textSize="13sp" android:text="(12.2M)"/> <TextView android:id="@+id/txtNewVersion" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_toRightOf="@+id/ivArrow" android:layout_marginTop="15dp" android:textColor="#999999" android:layout_marginLeft="5dp" android:textSize="13sp" android:text="V1.0.1"/> <ImageView android:id="@+id/ivArrow" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="22dp" android:layout_marginLeft="5dp" android:layout_toRightOf="@+id/txtOldVersion" app:srcCompat="@drawable/pic_update_arrow"/> <TextView android:id="@+id/txtOldVersion" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginTop="15dp" android:textColor="#999999" android:textSize="13sp" android:text="V1.0.0"/> <TextView android:id="@+id/txtUpdateData" android:layout_below="@+id/txtOldVersion" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="1dp" android:textSize="15sp" android:textColor="#999999" android:layout_marginLeft="15dp" android:gravity="center_horizontal" android:text="9月18号发布"/> <TextView android:id="@+id/txtUpdateContent" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/txtUpdateData" android:layout_marginTop="10dp" android:layout_marginLeft="15dp" android:text="@string/update_content" android:textColor="#333" android:textSize="17sp"/> <TextView android:id="@+id/lvUpdateCont" android:layout_width="match_parent" android:layout_height="200dp" android:scrollbars="vertical" android:layout_below="@+id/txtUpdateContent" android:text=" " android:layout_marginLeft="6dp" android:layout_marginTop="8dp" android:textColor="#666666" android:textSize="17sp"/> <ImageView android:id="@+id/btUpdate" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/lvUpdateCont" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:background="@drawable/bt_update_normal" android:clickable="true"/> </RelativeLayout> </RelativeLayout> </RelativeLayout>
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#c2c2c2"> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="false" android:layout_alignParentStart="false" android:layout_centerInParent="true" android:layout_centerVertical="true" android:background="#ffffff"> <RelativeLayout android:id="@+id/rlFindNewVersion" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/bg_update_normal"> <ImageView android:id="@+id/ivUpdateNewVersion" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:layout_marginTop="6dp" android:src="@drawable/pic_update_download"/> </RelativeLayout> <com.foxconn.ackh.cd.sf.entity.HorizontalProgressBarWithNumber android:id="@+id/hpbProgressUpdate" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_alignLeft="@+id/rlFindNewVersion" android:layout_alignRight="@+id/rlFindNewVersion" android:layout_marginLeft="15dp" android:layout_marginTop="100dp" app:progress_reached_color="#1d82d2" app:progress_unreached_color="#f2f2f2" android:padding="5dp"/> <Button android:id="@+id/btupdatecancle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/hpbProgressUpdate" android:layout_marginBottom="15dp" android:layout_toLeftOf="@+id/btBack" android:background="#00000000" android:text="取消" android:textColor="#999999" android:textSize="17sp"/> <Button android:id="@+id/btBack" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/hpbProgressUpdate" android:layout_alignRight="@+id/hpbProgressUpdate" android:layout_marginBottom="15dp" android:layout_marginRight="15dp" android:background="#00000000" android:text="后台下载" android:textColor="#1d82d2" android:textSize="17sp"/> </RelativeLayout> </RelativeLayout>
在上面的代码还有很多可以改善的地方
在主页面获取更新状态的时候用的是线程循环监控,但是这种方法不是很稳
比如某些机子很卡,循环了三次之后还是没有监控到更新状态,那这就是个问题
后面修改成用接口回调的方法
//发送信息到服务查看回调 Common.checkVersionUpdate(RxAppUtils.getAppVersionName(MainActivity.this), new IDataCallback() { @Override public void onDataChange(boolean isSuccess, Object Data, int rv, String msg) { if (isSuccess) { if (rv == 200) { System.out.println("........"+Data); onUpdate((UpdateStatus) Data,msg); } } } });
这上面是用接口获取到了信息
用之前首先得有一个接口,抽象一个方法
方法参数里面放需要用到的数据,这里需要用到的主要是登录状态
public abstract interface IDataCallback { public abstract void onDataChange( boolean isSuccess, Object Data ,int rv, String msg); }
然后在调用方法里加入这个接口,并将数据交到这个接口的方法里面
//检查版本更新,这里用得是Xutils提交数据请求服务器回调 public static void checkVersionUpdate(String versionName,final IDataCallback callback) { final String checkVersionUrl = UPDATE_URL + "token=" + "2b5c2d36fc41358c299f9230d8a15e501b45f1b473c0cbacb54afa7bdc03e800&" + "app_id=3&" + "os_type=android&" + "version=" + versionName; RequestParams requestParams = new RequestParams(checkVersionUrl); x.http().get(requestParams, new Callback.CommonCallback<String>() { @Override public void onSuccess(String result) { rver = new RequestVersion(result); Log.i("调回来的信息",result); if (rver.getRv()==200){ if (rver.isUpd()){ updateContent = rver.getChange();//获取更新的内容 //文件路径 apkPath = ROOT_URL + rver.getPath();//获取APK文件的服务器路径 //如果返回真,则要更新 //instance.updateMessage(IUpdateListener.UpdateStatus.YES,"YES"); callback.onDataChange(true, IUpdateListener.UpdateStatus.YES,rver.getRv(),rver.getMsg()); }else{ callback.onDataChange(true, IUpdateListener.UpdateStatus.NO,rver.getRv(),rver.getMsg()); //当前版本为最新,不用更新 //instance.updateMessage(IUpdateListener.UpdateStatus.NO,"NO"); } }else { Log.i("出错了,传回来的信息", rver.getMsg()); } } @Override public void onError(Throwable ex, boolean isOnCallback) { System.out.println("发送验证消息的时候发生了错误"); } @Override public void onCancelled(CancelledException cex) { } @Override public void onFinished() { } });