您好,登錄后才能下訂單哦!
1. VersionUpdate用于檢測是否有新版本,以及如果有新版本以何種方式提示給用戶。
public class VersionUpdate { private String TAG = "VersionUpdate"; public final String APK_URL = "http://gdown.baidu.com/data/wisegame/086ad68302fb074d/WeChat_352.apk"; private Context context; private UpdateManager updateManager; private int mUpdateRole = 12; // 版本更新用到 private UpdateListener updateListener; public void setUpdateListener(UpdateListener updateListener) { this.updateListener = updateListener; } public interface UpdateListener { public void onUpdate(double remoteVersion, double localVersion); } public VersionUpdate(Context context) { this.context = context; updateManager = new UpdateManager(context); } public void checkUpdate() { IVideoFetcher.CallBack callback = new IVideoFetcher.CallBackAdapter() { @Override public void onComplete(IVideoResult result) { if(!result.isSuccess()) return; VersionData data = (VersionData)result.getData(); if(data == null) return; data.setApkUrl(APK_URL); updateManager.setApkUrl(data.getApkUrl()); Log.i(TAG, new Gson().toJson(data)); double remoteVersion = 0.0; double localVersion = 0.0; try { remoteVersion = Double.valueOf(data.getVersion()); localVersion = Double.valueOf(getVersion()); mUpdateRole = Integer.valueOf(data.getRole()); } catch(NumberFormatException ex) { ex.printStackTrace(); } updateListener.onUpdate(remoteVersion, localVersion); } }; String url = IVideoURL.TvieURL.VERSION_URL; Map<String, String> params = new HashMap<String, String>(); params.put("version", getVersion()); params.put("productId", context.getPackageName()); params.put("platform", "android"); params.put("os", Build.VERSION.CODENAME); IVideoFetcher.doGet(VersionResult.class, callback, url, params); } public void confirmUpdate() { AlertDialog.Builder builder = new Builder(context); builder.setMessage("親,有更新版本的軟件包哦,請快下載更新吧"); builder.setTitle("更新提示"); builder.setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); updateManager.beginUpdate(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } public void alertNeedUpdate() { AlertDialog.Builder builder = new Builder(context); builder.setMessage("親,有更新版本的軟件包哦,請快下載更新吧"); builder.setTitle("更新提示"); builder.setPositiveButton("確認", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); updateManager.beginUpdate(); } }); builder.create().show(); } public void alertNoUpdate() { AlertDialog.Builder builder = new Builder(context); builder.setMessage("親,該版本已是最新版本,無需升級"); builder.setTitle("更新提示"); builder.setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } /** * 獲取版本號 * @return 當前應用的版本號 */ public String getVersion() { try { PackageManager manager = context.getPackageManager(); PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0); String version = info.versionName; return version; } catch (Exception e) { e.printStackTrace(); return "0.0"; } } public void update() { switch(mUpdateRole) { case 10: confirmUpdate(); break; case 11: alertNeedUpdate(); break; case 9: case 12: alertNoUpdate(); break; } } }
2. UpdateManager用于從服務端下載新的apk文件,下載完成提示用戶安裝。
public class UpdateManager { private Context mContext; //提示語 private String updateMsg = "有最新的軟件包哦,親快下載吧~"; //返回的安裝包url private String apkUrl; private Dialog noticeDialog; private Dialog downloadDialog; /* 下載包安裝路徑 */ // private static final String savePath = "/sdcard/com.tvie.xj.ivideo/"; private static final String savePath = TvieApplication.getInstance().getCacheDirPath(); private static final String saveFileName = savePath + "/com.tvie.xj.ivideo.apk"; /* 進度條與通知ui刷新的handler和msg常量 */ private ProgressBar mProgress; private TextView mProgressHint; private static final int DOWN_UPDATE = 1; private static final int DOWN_OVER = 2; private int progress; private int current; private int total; private Thread downLoadThread; private boolean interceptFlag = false; private Handler mHandler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what) { case DOWN_UPDATE: mProgress.setProgress(progress); mProgressHint.setText(DigitalUtil.toFileSizeFormat(mContext, current) +"/"+DigitalUtil.toFileSizeFormat(mContext, total)); break; case DOWN_OVER: if(downloadDialog != null) { downloadDialog.dismiss(); } installApk(); break; default: break; } }; }; public UpdateManager(Context context) { this.mContext = context; } public void setApkUrl(String apkUrl) { this.apkUrl = apkUrl; } //外部接口讓主Activity調用 public void checkUpdateInfo(){ showNoticeDialog(); } private void showNoticeDialog(){ AlertDialog.Builder builder = new Builder(mContext); builder.setTitle("軟件版本更新"); builder.setMessage(updateMsg); builder.setPositiveButton("下載", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); showDownloadDialog(); } }); builder.setNegativeButton("以后再說", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); noticeDialog = builder.create(); noticeDialog.show(); } public void beginUpdate(String apkUrl) { this.apkUrl = apkUrl; showDownloadDialog(); } public void beginUpdate() { showDownloadDialog(); } private void showDownloadDialog(){ AlertDialog.Builder builder = new Builder(mContext); builder.setTitle("正在下載新版本"); final LayoutInflater inflater = LayoutInflater.from(mContext); View v = inflater.inflate(R.layout.update_progress, null); mProgress = (ProgressBar)v.findViewById(R.id.progress); mProgressHint = (TextView)v.findViewById(R.id.progressHint); builder.setView(v); builder.setNegativeButton("取消", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); interceptFlag = true; mHandler.removeMessages(DOWN_UPDATE); mHandler.removeMessages(DOWN_OVER); } }); downloadDialog = builder.create(); downloadDialog.show(); downloadApk(); } private Runnable mdownApkRunnable = new Runnable() { @Override public void run() { try { URL url = new URL(apkUrl); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.connect(); int length = conn.getContentLength(); InputStream is = conn.getInputStream(); File file = new File(savePath); if(!file.exists()){ file.mkdir(); } File apkFile = new File(saveFileName); if(apkFile.exists()) { apkFile.delete(); } 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); current = count; total = length; //更新進度 mHandler.sendEmptyMessage(DOWN_UPDATE); if(numread <= 0){ //下載完成通知安裝 mHandler.sendEmptyMessage(DOWN_OVER); break; } fos.write(buf,0,numread); }while(!interceptFlag);//點擊取消就停止下載. if(interceptFlag && apkFile.exists()) { apkFile.delete(); } fos.close(); is.close(); conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } } }; /** * 下載apk * @param url */ private void downloadApk(){ interceptFlag = false; downLoadThread = new Thread(mdownApkRunnable); downLoadThread.start(); } /** * 安裝apk * @param url */ private void installApk(){ File apkfile = new File(saveFileName); if (!apkfile.exists()) { return; } Intent i = new Intent(Intent.ACTION_VIEW); i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive"); mContext.startActivity(i); } }
3. 以上兩個類經過驗證,可以直接利用,只需檢測新版本的代碼。下面給出版本更新的用法。
(1)在剛啟動應用時,檢測新版本,并提示用戶更新。
在MainActivity的onCreate方法中創建VersionUpdate對象,并檢測更新。
mVersionUpdate = new VersionUpdate(this); mVersionUpdate.setUpdateListener(updateListener); mVersionUpdate.checkUpdate();
其中UpdateListener定義為
VersionUpdate.UpdateListener updateListener = new VersionUpdate.UpdateListener() { @Override public void onUpdate(double remoteVersion, double localVersion) { if (remoteVersion > localVersion) { mVersionUpdate.update(); } } };
(2)在設置界面,檢測新版本,用戶點擊時提示用戶更新。
設置界面是一個Fragment,同樣也是在onCreate方法中創建VersionUpdate對象
mVersionUpdate = new VersionUpdate(getActivity()); mVersionUpdate.setUpdateListener(updateListener);
定義UpdateListener實例對象
VersionUpdate.UpdateListener updateListener = new VersionUpdate.UpdateListener() { @Override public void onUpdate(double remoteVersion, double localVersion) { if (remoteVersion > localVersion) { mNewFlag.setVisibility(View.VISIBLE); } else { mNewFlag.setVisibility(View.INVISIBLE); } } };
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。