App 版本更新 versionUpdate
極客學(xué)院30天免費(fèi)課程福利,大量VIP等著你領(lǐng)養(yǎng),想在線學(xué)編程的小伙伴速來(lái),手快戳
極客學(xué)院的學(xué)習(xí)記錄:
App 版本更新步驟:
1、checkUpdate()//檢測(cè)版本是否需要更新
2、downLoadAPK()//下載新版本的APP
3、installAPK()//安裝新版本APP
分析:
1、線上線下版本號(hào)比對(duì),判斷是否需要更新:
1)訪問(wèn)服務(wù)器 請(qǐng)求服務(wù)器中App 版本信息。
2)查詢本地App版本信息。
2、是否更新:
1)有新版本需要更新:
使用對(duì)話框詢問(wèn)用戶是否選擇更新
showNoticeDialog();
2)沒(méi)有新版本不更新:
提示:已經(jīng)是最新版本不需要更新。
3、更新:
downLoadAPK();
showDownLoadDialog() ;//顯示現(xiàn)在進(jìn)度
4、安裝:installAPK;
使用Android自帶安裝方式安裝。
java Code:
package com.autoupdate.zyh;import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL;import org.json.JSONException; import org.json.JSONObject;import android.app.AlertDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; 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.Toast;import com.android.volley.RequestQueue; import com.android.volley.Response.ErrorListener; import com.android.volley.Response.Listener; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley;/*** @author zyh* @version 創(chuàng)建時(shí)間:2015年7月28日 上午9:10:31 類說(shuō)明:*/ public class UpdateManager {private ProgressBar mProgressbar;private int mProgress;private Dialog mDownLoadDialog;private String mSavefilePath;// 下載的APK 保存地址private static final String path = "http://aps.yuandaitong.com/index.php?a=seed";private static final int DOWNLOADING = 1;// 加載中private static final int DOWNLOAD_FINISH = 2;// 加載完成private String mVersion_name; // APk名稱private String mVersion_code;// apk版本號(hào)private String mVersion_desc;// 更新版本描述private String mVersion_path;// 下載 Apk 地址private boolean mIsCancel;// 是否取消下載private Context mContext;private Handler mHandler = new Handler() {public void handleMessage(Message msg) {try {Log.i("volley", msg.toString());JSONObject jsonObj = (JSONObject) msg.obj;String jsonStr = jsonObj.getString("data");JSONObject obj = new JSONObject(jsonStr);mVersion_code = obj.getString("version_code");mVersion_desc = obj.getString("version_desc");mVersion_name = obj.getString("version_name");mVersion_path = obj.getString("version_path");if (isUpdate()) {showNoticeDialog();} else {Toast.makeText(mContext, "已經(jīng)是最新版本", 1).show();}Log.i("volley", mVersion_path);} catch (JSONException e) {e.printStackTrace();}};};private Handler mUpdateProgressHandler = new Handler() {public void handleMessage(Message msg) {switch (msg.what) {case DOWNLOADING:// 更新當(dāng)前進(jìn)度mProgressbar.setProgress(mProgress);break;case DOWNLOAD_FINISH:// 隱藏 下載對(duì)話框mDownLoadDialog.dismiss();// 安裝下載的apkinstallAPK();break;default:break;}};};public UpdateManager(Context context) {this.mContext = context;}/*** 檢測(cè)軟件是否需要更新*/public void checkUpdate() {RequestQueue requestQueue = Volley.newRequestQueue(mContext);JsonObjectRequest request = new JsonObjectRequest(path, null,new Listener<JSONObject>() {@Overridepublic void onResponse(JSONObject response) {Message msg = Message.obtain();msg.obj = response;mHandler.sendMessage(msg);}}, new ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {}});requestQueue.add(request);}/** 與本地版本比較判斷是否需要更新* * @return*/protected boolean isUpdate() {int serverVersion = Integer.valueOf(mVersion_code);int localVersion = 1;try {localVersion = mContext.getPackageManager().getPackageInfo("com.autoupdate.zyh", 0).versionCode;} catch (NameNotFoundException e) {e.printStackTrace();}if (serverVersion > localVersion) {return true;}return false;}/** 有更新時(shí)提示對(duì)話框*/protected void showNoticeDialog() {AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);dialog.setTitle("提示").setMessage("有新版發(fā)布,需要更新\n" + mVersion_desc).setNegativeButton("取消", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();}}).setPositiveButton("去更新", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {showDownLoadDialog();dialog.dismiss();}}).create().show();}/** 顯示下載進(jìn)度 的對(duì)話框*/protected void showDownLoadDialog() {View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_progress, null);AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);dialog.setTitle("下載中").setView(view);mProgressbar = (ProgressBar) view.findViewById(R.id.id_progress);dialog.setNegativeButton("取消", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// 取消對(duì)話框dialog.dismiss();mIsCancel = true;// 取消下載}});mDownLoadDialog = dialog.create();mDownLoadDialog.show();// TODO 下載APKdownLoadAPK();}/** 下載APK文件*/private void downLoadAPK() {new Thread() {public void run() {InputStream in = null;FileOutputStream out = null;try {if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {String SDpath = Environment.getExternalStorageDirectory() + File.separator;mSavefilePath = SDpath + "DownLoadAPKS";File dir = new File(mSavefilePath);if (!dir.exists()) {dir.mkdir();}HttpURLConnection conn = (HttpURLConnection) new URL(mVersion_path).openConnection();conn.setDoInput(true);conn.setDoOutput(true);conn.setConnectTimeout(30 * 1000);conn.connect();in = conn.getInputStream();int length = conn.getContentLength();File apkFile = new File(mSavefilePath, mVersion_name);out = new FileOutputStream(apkFile);int count = 0;byte[] buffer = new byte[1024];while (!mIsCancel) {int numRead = in.read(buffer);count += numRead;// 計(jì)算進(jìn)度條當(dāng)前位置mProgress = (int) ((float) count / length * 100);mUpdateProgressHandler.sendEmptyMessage(DOWNLOADING);// 下載完成if (numRead < 0) {mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_FINISH);break;}out.write(buffer, 0, numRead);}}} catch (Exception e) {e.printStackTrace();} finally {try {out.close();in.close();} catch (Exception e2) {}}};}.start();}private void installAPK() {File apkFile = new File(mSavefilePath, mVersion_name);if (!apkFile.exists()) {return;}Intent intent = new Intent(Intent.ACTION_VIEW);Uri uri = Uri.parse("file://" + apkFile.toString());intent.setDataAndType(uri, "application/vnd.android.package-archive");mContext.startActivity(intent);}}Dialog.xml:
?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="vertical" ><ProgressBarandroid:id="@+id/id_progress"style="?android:attr/progressBarStyleHorizontal"android:layout_width="match_parent"android:layout_height="wrap_content" /></LinearLayout>說(shuō)明:
(一)使用方式
public class MainActivity extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);new UpdateManager(this).checkUpdate();//看這里}}(二)這是Volley 框架 具體的Jar包 在文章結(jié)尾的源碼中有 ,而且不需要積分。
/*** 檢測(cè)軟件是否需要更新*/public void checkUpdate() {RequestQueue requestQueue = Volley.newRequestQueue(mContext);JsonObjectRequest request = new JsonObjectRequest(path, null,new Listener<JSONObject>() {@Overridepublic void onResponse(JSONObject response) {Message msg = Message.obtain();msg.obj = response;mHandler.sendMessage(msg);}}, new ErrorListener() {@Overridepublic void onErrorResponse(VolleyError error) {}});requestQueue.add(request);}免費(fèi)源碼下載
總結(jié)
以上是生活随笔為你收集整理的App 版本更新 versionUpdate的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 工作169:vue项目报错[Vue wa
- 下一篇: 前端学习(2583):生态圈练习解答下