標籤:service out protect pen bool message 小數 大神 dem
其實這不是什麼難事了,都有熱更新的技術了,只是記錄一下,大神勿嘲笑。
先說下思路,首先要有更新的介面,只要進入app,就監測一下介面,是否更新,更新的話,檢測本地版本是否低於介面返回的版本,低的話,就根據返回的路徑下載apk更新。介面返回的欄位起碼有 更新標誌、更新版本,更新描述,apk。
更新標誌應該有三種狀態,更新,詢問更新,強制更新,可以啟動一個Service(不要忘記在資訊清單檔中註冊)來進行檢查更新以及下載的工作;
這下面就是 Service裡的全部代碼,也不是很難理解,重要的地方都有注釋。寫好Service後,在代碼中 startService()啟動就可以了。
這裡面彈出了一個訊問框,需要在資訊清單檔中 加入許可權, <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />,這是彈出全域訊問框的許可權。
import android.app.AlertDialog;import android.app.Dialog;import android.app.Service;import android.content.DialogInterface;import android.content.Intent;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.graphics.Color;import android.net.Uri;import android.os.Environment;import android.os.Handler;import android.os.IBinder;import android.os.Message;import android.support.annotation.Nullable;import android.util.Log;import android.view.LayoutInflater;import android.view.View;import android.view.WindowManager;import android.widget.ProgressBar;import android.widget.TextView;import com.example.sdtz.wenmingweifang.R;import com.example.sdtz.wenmingweifang.Tool.OkHttpUtil;import com.example.sdtz.wenmingweifang.Util.App;import com.example.sdtz.wenmingweifang.Util.MyUrl;import org.json.JSONException;import org.json.JSONObject;import java.io.File;import java.io.FileOutputStream;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;/** * Created by sdtz on 2017/7/1. */public class UpdateService extends Service { private ProgressBar mProgressBar;//進度條 private TextView tv1; private TextView tv2; private String url = MyUrl.Httpurl; private String VersionCode; private String result; private App app; private String mSavePath;//apk儲存地址 private String mVersion_path; private String mVersion_name = "app.apk";//apk名 private float length; private Dialog mDownloadDialog;//對話方塊 private int mProgress;//進度值 private static final int DOWNLOADING = 1;//apk下載中 private static final int DOWNLOAD_FINISH = 2;//apk下載完畢 private boolean mIsCancel = false;//是否取消下載標示符 @Nullable @Override public IBinder onBind(Intent intent) { return null; } private Handler mUpdateProgressHandler = new Handler(){ public void handleMessage(Message msg) { switch (msg.what){ case DOWNLOADING: // 設定進度條 mProgressBar.setProgress(mProgress); tv1.setText( mProgress + "/100"); float len = length/1024/1024;//將length轉換為M單位 float b = (float)(Math.round(len*100))/100;//保留兩位小數點 tv2.setText( b+"M"); break; case DOWNLOAD_FINISH: // 隱藏當前下載對話方塊 mDownloadDialog.dismiss(); // 安裝 APK 檔案 installAPK(); break; default: break; } }; }; @Override public int onStartCommand(Intent intent, int flags, int startId) { try { VersionCode = getVersionName(); /* getJsonReuslt();*/ new OkHttpUtil().getJson(MyUrl.appdown, new OkHttpUtil.HttpCallBack() { @Override public void onSusscess(String data) throws JSONException { JSONObject jo1 = new JSONObject(data); app = new App(); app.setVersion(jo1.getString("version").toString()); app.setDescription(jo1.getString("description").toString()); app.setUrl(MyUrl.Httpurl+jo1.getString("url").toString()); app.setUpdate_flag(jo1.getString("update_flag").toString()); mVersion_path = app.getUrl(); //手機目前的版本 String phoneVersion = VersionCode.substring(0,VersionCode.lastIndexOf(".")); Double jiekou = Double.parseDouble(app.getVersion()); Double bendi = null; try { bendi = Double.parseDouble(getVersionName()); } catch (Exception e) { e.printStackTrace(); } Log.d("==","介面:"+jiekou+"本地:"+bendi+"::"+app.toString()); //本地版本 與 介面返回版本 不一致,並且 更新標誌為1 ,則更新 if( !VersionCode.equals(app.getVersion()) && (jiekou>bendi) && app.getUpdate_flag().equals("1")){ Log.d("==","::進入"); showDialog(app.getDescription()); }else if( !VersionCode.equals(app.getVersion()) && (jiekou>bendi) && app.getUpdate_flag().equals("2")){ showDownloadDialog(); } } }); } catch (Exception e) { e.printStackTrace(); } catch (Throwable throwable) { throwable.printStackTrace(); } return super.onStartCommand(intent, flags, startId); } /* * 擷取當前程式的版本號碼 */ private String getVersionName() throws Exception{ //擷取packagemanager的執行個體 PackageManager packageManager = getPackageManager(); //getPackageName()是你當前類的包名,0代表是擷取版本資訊 PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0); return packInfo.versionName; } private void showDialog(String drc) { final AlertDialog.Builder builder = new AlertDialog.Builder(this,AlertDialog.THEME_HOLO_LIGHT); builder.setMessage(drc); builder.setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { showDownloadDialog(); } }); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }); AlertDialog alertDialog = builder.create(); alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); alertDialog.setCanceledOnTouchOutside(true); alertDialog.show(); alertDialog.getButton(alertDialog.BUTTON_POSITIVE).setTextColor(Color.GREEN); alertDialog.getButton(alertDialog.BUTTON_NEGATIVE).setTextColor(Color.RED); } /* * 開啟新線程下載檔案 */ private void downloadAPK() { new Thread(new Runnable() { @Override public void run() { try{//檢查sd是否掛載 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ String sdPath = Environment.getExternalStorageDirectory() + "/"; mSavePath = sdPath + "WenmingDownload"; File dir = new File(mSavePath); if (!dir.exists()) dir.mkdir(); // 下載檔案 HttpURLConnection conn = (HttpURLConnection) new URL(mVersion_path).openConnection(); conn.connect(); InputStream is = conn.getInputStream(); length = conn.getContentLength(); File apkFile = new File(mSavePath, mVersion_name); FileOutputStream fos = new FileOutputStream(apkFile); int count = 0; byte[] buffer = new byte[1024]; while (!mIsCancel){ int numread = is.read(buffer); count += numread; // 計算進度條的當前位置 mProgress = (int) ((count/length) * 100); // 更新進度條 mUpdateProgressHandler.sendEmptyMessage(DOWNLOADING); // 下載完成 if (numread < 0){ mUpdateProgressHandler.sendEmptyMessage(DOWNLOAD_FINISH); break; } fos.write(buffer, 0, numread); } fos.close(); is.close(); } }catch(Exception e){ e.printStackTrace(); } } }).start(); } /* * 下載到本地後執行安裝 */ protected void installAPK() { File apkFile = new File(mSavePath, 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"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); this.startActivity(intent); } /* * 顯示正在下載對話方塊 */ protected void showDownloadDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("版本更新,下載中。。。"); View view = LayoutInflater.from(this).inflate(R.layout.dialog_progress, null); mProgressBar = (ProgressBar) view.findViewById(R.id.id_progress); tv1 = (TextView) view.findViewById(R.id.tv1); tv2 = (TextView) view.findViewById(R.id.tv2); builder.setView(view); mDownloadDialog = builder.create(); mDownloadDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); mDownloadDialog.show(); // 下載檔案 downloadAPK(); }}
android 實現檢測版本,下載apk更新(附源碼)