大部分應用可在自己后台實現更新功能,有些項目沒有后台,可使用fir.im提供的更新接口,方便好用。
1、在 fir.im 申請賬號后,拖拽apk包上傳應用
2、調用版本查詢接口, http://api.fir.im/apps/latest/,傳入應用id,應用id在基本信息里查看
String url = "http://api.fir.im/apps/latest/58c2060c959d690ca80000ab"; OkHttpUtils .get() .url(url) .addParams("api_token", "76781495449213ac787a0fd3b9923a2b") .build() .execute(new StringCallback() { @Override public void onError(Call call, Exception e, int id) { Log.d("err===========",e + ""); } @Override public void onResponse(String response, int id) { Log.d("ok===========",response); Gson gson = new Gson(); CheckBean bean = gson.fromJson(response,CheckBean.class); if (getVersionCode(mContext) < bean.getVersion()){ showSimpleDialog(bean.getChangelog(),bean.getInstall_url()); }else { Toast.makeText(mContext,"暫無更新",Toast.LENGTH_SHORT).show(); } } });
可用gson解析返回數據,數據包括
應用名、version版本、更新日志、下載地址
3、獲取本地version,與返回version對比
public static int getVersionCode(Context mContext) { if (mContext != null) { try { return mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode; } catch (PackageManager.NameNotFoundException ignored) { } } return 0; }
4、有新的版本時,使用install_url下載apk
OkHttpUtils// .get()// .url(url)// .build()// .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "shzs.apk") { @Override public void onError(Call call, Exception e, int id) { Log.d("err=======",e + ""); } @Override public void onResponse(File response, int id) { Log.d("ok==========",response.toString()); installAPK(response); } @Override public void inProgress(float progress, long total, int id) { Log.d("pro==========",progress + ""); super.inProgress(progress, total, id); } });
可在inProgress中查看進度。
5、下載到本地后,自動安裝
private void installAPK(File file) { if (!file.exists()) return; Intent intent = new Intent(Intent.ACTION_VIEW); Uri uri = Uri.parse("file://" + file.toString()); intent.setDataAndType(uri, "application/vnd.android.package-archive"); //在服務中開啟activity必須設置flag, intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); }
到此,更新完成。