Android 检查版本更新 Server后台下载
生活随笔
收集整理的這篇文章主要介紹了
Android 检查版本更新 Server后台下载
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
問題來了,平時開發應用也許你會遇到這種場景:應用啟動檢查服務器版本,若大于當前版本,則要從網絡上下載APK文件,并在Activity上展示進度條。
版本更新,無非是下載apk文件,安裝apk。
//其中用到 Xutils
ublic class CheckVersionUtils {private static CheckVersionUtils mCheckVersionUtils;private CheckVersionUtils() {}public static CheckVersionUtils getInstance() {if (mCheckVersionUtils == null) {mCheckVersionUtils = new CheckVersionUtils();}return mCheckVersionUtils;}/*** 訪問網絡檢查版本號碼** @param isToastNoVersion 是否彈出"當前版本已為最新版本"的Toast* @param activity 彈窗需要的依賴的Activity*/public void checkVersionToServer(final boolean isToastNoVersion, final Activity activity) {x.http().get(new RequestParams(ConstantValue.CHECK_VERSION_JSON_URL), new Callback.CommonCallback<String>() {@Overridepublic void onSuccess(String result) {Log.e("CheckVersionActivity", "CheckVersionActivity onSuccess()" + result);processData(result, activity, isToastNoVersion);}@Overridepublic void onError(Throwable ex, boolean isOnCallback) {}@Overridepublic void onCancelled(CancelledException cex) {}@Overridepublic void onFinished() {}});}/*** 返回版本號*/private int getVersionCode() {return BuildConfig.VERSION_CODE;}/*** 解析JSON** @param json* @param isToastNoVersion*/private void processData(String json, Activity activity, boolean isToastNoVersion) {Gson gson = new Gson();CheckVersionBean checkVersionBean = gson.fromJson(json, CheckVersionBean.class);/*** 保存在手機的位置*/String saveSDPath = EXB_SD_PATH_APK + checkVersionBean.getFileName();//判斷是否需要更新if (getVersionCode() < checkVersionBean.getVersionCode()) {showUpdateDialog(checkVersionBean, saveSDPath, activity);} else {if (isToastNoVersion) {//不更新Toast.makeText(activity, "當前版本已為最新版本", Toast.LENGTH_SHORT).show();}}}/*** 顯示更新對話框** @param checkVersionBean*/private void showUpdateDialog(final CheckVersionBean checkVersionBean, final String saveSDPath, final Activity activity) {//創建文件,判斷是否存在AlertDialog.Builder builder = new AlertDialog.Builder(activity);AlertDialog alertDialog = builder.create();//更新描述信息String updateLog = checkVersionBean.getUpdateLog();if (TextUtils.isEmpty(updateLog)) {updateLog = "新版本,歡迎更新";}//版本名稱String versionName = checkVersionBean.getVersionName();if (TextUtils.isEmpty(versionName)) {versionName = "1.1";}alertDialog.setTitle("新版本" + versionName);alertDialog.setMessage(updateLog);//判斷是否要強制更新if (checkVersionBean.getIsForceUpdate() == 1) {//強制更新//設置外部點了沒有效果alertDialog.setCanceledOnTouchOutside(false);//禁用返回鍵alertDialog.setCancelable(false);alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "更新", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {//更新downloadApk(checkVersionBean.getDownloadUrl(), saveSDPath, activity);}});} else {alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {}});alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "更新", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {//更新downloadApk(checkVersionBean.getDownloadUrl(), saveSDPath, activity);}});}alertDialog.show();}/*** 下載apk** @param downurl*/private void downloadApk(String downurl, String path, final Activity activity) {final ProgressDialog progressDialog = new ProgressDialog(activity);RequestParams requestParams = new RequestParams(downurl);requestParams.setSaveFilePath(path);x.http().get(requestParams, new Callback.ProgressCallback<File>() {@Overridepublic void onWaiting() {}@Overridepublic void onStarted() {}@Overridepublic void onLoading(long total, long current, boolean isDownloading) {progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);progressDialog.setMessage("拼命下載中...");progressDialog.show();progressDialog.setMax(100);double fcurrent = current;progressDialog.setProgress((int) ((fcurrent / total) * 100));}@Overridepublic void onSuccess(File result) {Toast.makeText(NiceyooApplication.getNiceyooApp(), "下載完成", Toast.LENGTH_SHORT).show();progressDialog.dismiss();installApk(activity, result);}@Overridepublic void onError(Throwable ex, boolean isOnCallback) {ex.printStackTrace();Toast.makeText(NiceyooApplication.getNiceyooApp(), "下載失敗,請檢查網絡和SD卡", Toast.LENGTH_SHORT).show();progressDialog.dismiss();}@Overridepublic void onCancelled(CancelledException cex) {}@Overridepublic void onFinished() {}});}/*** 安裝對應apk** @param activity* @param file 安裝文件*/private void installApk(Activity activity, File file) {//系統應用界面,源碼,安裝apk入口Intent intent = new Intent("android.intent.action.VIEW");intent.addCategory("android.intent.category.DEFAULT");//設置安裝的類型intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");activity.startActivityForResult(intent, ConstantValue.INSTALL_NEW_VERSION_SUCCESS);} }上邊代碼不是server下載
為什么要用server下載呢?因為有可能 你需要更新的這個Activity要求是可以轉屏的。那么在轉屏時Actvitiy會重啟,如何保證下載的進度條能正確展示進度呢?當然是用server下載了…
public class UpdateService extends Service {public UpdateService() {}/*** 安卓系統下載類**/DownloadManager manager;/*** 接收下載完的廣播**/DownloadCompleteReceiver receiver;/*** 初始化下載器**/private void initDownManager() {manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);receiver = new DownloadCompleteReceiver();//設置下載地址DownloadManager.Request down = new DownloadManager.Request(// 百度音樂Uri.parse("http://gdown.baidu.com/data/wisegame/fd84b7f6746f0b18/baiduyinyue_4802.apk"));// 樂視體育// Uri.parse("http://122.228.237.132/apk.r1.market.hiapk.com/data/upload/apkres/2016/6_12/16/com.lesports.glivesports_040405.apk"));// 設置允許使用的網絡類型,這里是移動網絡和wifi都可以down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);// 下載時,通知欄顯示途中if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {down.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);}// 顯示下載界面down.setVisibleInDownloadsUi(true);// 設置下載后文件存放的位置down.setDestinationInExternalFilesDir(this, Environment.DIRECTORY_DOWNLOADS, "leshi.apk");// 將下載請求放入隊列manager.enqueue(down);//注冊下載廣播registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {// 調用下載initDownManager();return super.onStartCommand(intent, flags, startId);}@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic void onDestroy() {// 注銷下載廣播if (receiver != null)unregisterReceiver(receiver);super.onDestroy();}// 接受下載完成后的intentclass DownloadCompleteReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {//判斷是否下載完成的廣播if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {//獲取下載的文件idlong downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);//自動安裝apkif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {Uri uriForDownloadedFile = manager.getUriForDownloadedFile(downId);Log.d("kodulf", "uri=" + uriForDownloadedFile);installApkNew(uriForDownloadedFile);}//停止服務并關閉廣播UpdateService.this.stopSelf();}}//安裝apkprotected void installApkNew(Uri uri) {Intent intent = new Intent();//執行動作intent.setAction(Intent.ACTION_VIEW);//執行的數據類型intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setDataAndType(uri, "application/vnd.android.package-archive");//不加下面這句話是可以的,查考的里面說如果不加上這句的話在apk安裝完成之后點擊單開會崩潰// android.os.Process.killProcess(android.os.Process.myPid());startActivity(intent);}} }
參考:http://blog.csdn.net/rodulf/article/details/51706788#comments
下載demo
總結
以上是生活随笔為你收集整理的Android 检查版本更新 Server后台下载的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Vue.js(2.x)之Class 与
- 下一篇: android sina oauth2.