Android 一s个相对完整的自动升级功能实现代码
生活随笔
收集整理的這篇文章主要介紹了
Android 一s个相对完整的自动升级功能实现代码
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
由于項(xiàng)目的需要最近做了一個(gè)關(guān)于Android自動升級的功能,下面將貼出Android手機(jī)客戶端的完整代碼。這段代碼參考別的代碼居多,由于不滿足需求,所以自己僅僅改了一些需要變動的內(nèi)容,其他功能都是按照原作者的代碼來寫的。希望能夠給大家提供幫助。
package com.example.myapi; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.List;import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; 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;public class UpdateManager { /* 下載中 */ private static final int DOWNLOAD = 1; /* 下載結(jié)束 */ private static final int DOWNLOAD_FINISH = 2; /* 下載保存路徑 */ private String mSavePath; /* 記錄進(jìn)度條數(shù)量 */ private int progress; /* 是否取消更新 */ private boolean cancelUpdate = false; private Context mContext; /* 更新進(jìn)度條 */ private ProgressBar mProgress; private Dialog mDownloadDialog; private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { // 正在下載 case DOWNLOAD: // 設(shè)置進(jìn)度條位置 mProgress.setProgress(progress); break; case DOWNLOAD_FINISH: // 安裝文件 installApk(); break; case 200://服務(wù)端信息//如果有新版本checkUpdate();//更新信息break;case 101:Toast.makeText(mContext, "手機(jī)中沒有內(nèi)存卡,無法安裝!", Toast.LENGTH_LONG).show(); break;default: break; } }; }; public UpdateManager(Context context) { this.mContext = context; /*** 此段代碼是用于檢測版本是否有升級* 如果有升級則向handler發(fā)送200*/mHandler.sendEmptyMessage(200);} /** * 檢測軟件更新 */ public void checkUpdate() { showNoticeDialog(); } /** * 檢查軟件是否有更新版本 * * @return */ private boolean isUpdate(){ return false; } /** * 獲取軟件版本號 * * @param context * @return */ private int getVersionCode(Context context) { int versionCode = 0; try { // 獲取軟件版本號,對應(yīng)AndroidManifest.xml下android:versionCode versionCode = context.getPackageManager().getPackageInfo("com.szy.update", 0).versionCode; } catch (NameNotFoundException e) { e.printStackTrace(); } return versionCode; } /** * 顯示軟件更新對話框 */ private void showNoticeDialog() { // 構(gòu)造對話框 AlertDialog.Builder builder = new Builder(mContext); builder.setTitle("提示"); builder.setMessage("已檢測到軟件更新");// 更新 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(); } }); Dialog noticeDialog = builder.create(); noticeDialog.setCanceledOnTouchOutside(false);noticeDialog.show(); } /** * 顯示軟件下載對話框 */ private void showDownloadDialog() { // 構(gòu)造軟件下載對話框 AlertDialog.Builder builder = new Builder(mContext); builder.setTitle("提示"); // 給下載對話框增加進(jìn)度條 final LayoutInflater inflater = LayoutInflater.from(mContext); View v = inflater.inflate(R.layout.softupdate_progress, null); mProgress = (ProgressBar) v.findViewById(R.id.update_progress); builder.setView(v); // 取消更新 builder.setNegativeButton("取消", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); // 設(shè)置取消狀態(tài) cancelUpdate = true; } }); mDownloadDialog = builder.create(); mDownloadDialog.setCanceledOnTouchOutside(false);mDownloadDialog.show(); // 現(xiàn)在文件 downloadApk(); } /** * 下載apk文件 */ private void downloadApk() { // 啟動新線程下載軟件 new downloadApkThread().start(); } /** * 下載文件線程 * * */ private class downloadApkThread extends Thread { @Override public void run() { try { // 判斷SD卡是否存在,并且是否具有讀寫權(quán)限 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // 獲得存儲卡的路徑 String sdpath = Environment.getExternalStorageDirectory() + "/"; mSavePath = sdpath + "fortrundownload"; URL url = new URL(/*此處填寫下載文件的路徑*/""); // 創(chuàng)建連接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); // 獲取文件大小 int length = conn.getContentLength(); // 創(chuàng)建輸入流 InputStream is = conn.getInputStream(); File file = new File(mSavePath); // 判斷文件目錄是否存在 if (!file.exists()) { file.mkdir(); } File apkFile = new File(mSavePath, "此處填寫文件的名稱(apk名稱)"); FileOutputStream fos = new FileOutputStream(apkFile); int count = 0; // 緩存 byte buf[] = new byte[1024]; // 寫入到文件中 do { int numread = is.read(buf); count += numread; // 計(jì)算進(jìn)度條位置 progress = (int) (((float) count / length) * 100); // 更新進(jìn)度 mHandler.sendEmptyMessage(DOWNLOAD); if (numread <= 0) { // 下載完成 mHandler.sendEmptyMessage(DOWNLOAD_FINISH); break; } // 寫入文件 fos.write(buf, 0, numread); } while (!cancelUpdate);// 點(diǎn)擊取消就停止下載. fos.close(); is.close(); }else{//如果不存在內(nèi)存卡,則將下載下來的apk文件存入手機(jī)內(nèi)存mSavePath = "/data/data/com.fortrun.quickrecieve/files";File file = new File(mSavePath);Log.e("savepath", mSavePath);URL url = new URL("apk文件下載路徑"); // 創(chuàng)建連接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); // 獲取文件大小 int length = conn.getContentLength(); Log.e("startlength", length+"");// 創(chuàng)建輸入流 InputStream is = conn.getInputStream(); // 判斷文件目錄是否存在 if(file.exists()){file.delete();}if (!file.exists()) { boolean flag = file.mkdir();Log.e("flag", flag+"");}/* // 設(shè)置權(quán)限String command = "chmod 666" + file.getAbsolutePath();;Runtime runtime = Runtime.getRuntime();runtime.exec(command);// ContextWrapper cw = new ContextWrapper(mContext); // File directory = cw.getDir("media", Context.MODE_PRIVATE); // File apkFile = cw.getDir(mSavePath+"/"+msg9902.getFileName(), Context.MODE_PRIVATE);File apkFile = new File(mSavePath,msg9902.getFileName()); String commandFile = "chmod 666" + apkFile.getAbsolutePath();Log.e("apkfile", apkFile.getAbsolutePath());Runtime runtimeFile = Runtime.getRuntime();runtimeFile.exec(commandFile);*/ // FileOutputStream fos = new FileOutputStream(apkFile);//644標(biāo)記改程序有讀、寫、運(yùn)行權(quán)限/* String command = "chmod 644 " + mSavePath+"/"+msg9902.getFileName();String command2 = "chmod 777 " + mSavePath;Runtime runtime = Runtime.getRuntime();try {runtime.exec(command2);runtime.exec(command);} catch (IOException e) {e.printStackTrace();}*/FileOutputStream fos=(FileOutputStream)mContext.openFileOutput("apk文件名稱", mContext.MODE_WORLD_READABLE|mContext.MODE_WORLD_WRITEABLE);int count = 0; // 緩存 byte buf[] = new byte[1024]; // 寫入到文件中 do { int numread = is.read(buf); count += numread; // 計(jì)算進(jìn)度條位置 progress = (int) (((float) count / length) * 100); // 更新進(jìn)度 mHandler.sendEmptyMessage(DOWNLOAD); if (numread <= 0) { // 下載完成 mHandler.sendEmptyMessage(DOWNLOAD_FINISH); break; } // 寫入文件 fos.write(buf, 0, numread); } while (!cancelUpdate);// 點(diǎn)擊取消就停止下載. fos.flush();fos.close(); is.close(); }} catch (MalformedURLException e) { Log.e("downloadApkThread", e.getMessage());} catch (IOException e) { Log.e("downloadApkThread", e.getMessage());} // 取消下載對話框顯示 mDownloadDialog.dismiss(); } }; /** * 安裝APK文件 */ private void installApk() { //之前是604,705/*標(biāo)注擁有最高權(quán)限*//* String command = "chmod 644 " + mSavePath+"/"+msg9902.getFileName();String command2 = "chmod 777 " + mSavePath;Runtime runtime = Runtime.getRuntime();try {runtime.exec(command2);runtime.exec(command);} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}*/File apkfile = new File(mSavePath,"apk文件名稱");if (!apkfile.exists()) { return; } Intent i = new Intent(Intent.ACTION_VIEW);/*** i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); *這段代碼在Android4.0一下的系統(tǒng)中沒必要寫,* 但是如果是在Android4.0以上的系統(tǒng)中進(jìn)行安裝,就必須要寫上了。因?yàn)槿绻悴粚懮暇蜁? 出現(xiàn)在安裝的過程中莫名其妙的關(guān)掉,并且不會提示安裝完成。*/i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");mContext.startActivity(i); } }大家復(fù)制粘貼一下,然后修改下載路徑后就能夠直接使用了,哈哈。
轉(zhuǎn)載于:https://www.cnblogs.com/tony-yang-flutter/p/Androidupdates.html
總結(jié)
以上是生活随笔為你收集整理的Android 一s个相对完整的自动升级功能实现代码的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 喵喵折骗局
- 下一篇: Github管理Eclipse分布式项目