android應用apk升級更新
阿新 • • 發佈:2018-12-25
一、前言
這段時間獨立完成了一個專案,想把一些常用知識點記錄下來,如有不足之處還請指點。望共勉之。好啦,廢話不多說直接進入正題,直接上程式碼,效果圖我就不上了,程式碼是小編親測有效,大家放心好啦。
1.首先進行本地版本與伺服器版本對比,這都是老套路啦(^_^)
HttpHelper.obtain().Get(Constant.UpdateUrl, null, new ICallback() { @Override public boolean onSucess(String result) { updateBean = new Gson().fromJson(result, UpdateBean.class); int versionCode = FileProvider7Utils.getVersionName(MainActivity.this); Log.i("222", versionCode + ""); //伺服器版本 int verCode = Integer.parseInt(updateBean.getVerCode()); if (verCode > versionCode) { manager = new UpdateManager(MainActivity.this); manager.showDialog(Constant.DownAPk + updateBean.getApkName(),updateBean.getVerDesc()); } return false; } @Override public void onFailure(String e) { Toast.makeText(MainActivity.this, "" + e.toString(), Toast.LENGTH_SHORT).show(); } });
2.取得版本號
public static int getVersionName(Context context) { int VersionName=0; PackageManager packageManager=context.getPackageManager(); PackageInfo packageInfo; try { packageInfo=packageManager.getPackageInfo(context.getPackageName(),0); VersionName=packageInfo.versionCode; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } return VersionName; }
3.UpdateManager更新類
package com.kyny.workgroup.utils; 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.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.kyny.workgroup.R; import com.kyny.workgroup.model.UpdateBean; 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; /** *更新工具類 */ public class UpdateManager { private Dialog dialog; private UpdateBean updateBean; private static final String savePath = Environment .getExternalStorageDirectory().getPath() + "/本地檔名/"; private static final String saveFileName = savePath + "xx.apk"; private ProgressBar mProgress; private boolean interceptFlag = false; private String loadApkUrl; private int progress; private static final int DOWN_UPDATE = 1; private static final int DOWN_OVER = 2; private Context mContext; private Dialog downloadDialog; private TextView tvProgress; public UpdateManager(Context mContext) { this.mContext = mContext; } private Handler mHandler=new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case DOWN_UPDATE: mProgress.setProgress(progress); tvProgress.setText(progress+"%"); break; case DOWN_OVER: installApk(); break; } } }; /** * 安裝apk */ private void installApk() { File apkfile = new File(saveFileName); if (!apkfile.exists()) { return; } Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(android.content.Intent.ACTION_VIEW); // Uri uriForFile = FileProvider7Utils.getUriForFile(mContext, apkfile); FileProvider7Utils.setIntentDataAndType(mContext,intent, "application/vnd.android.package-archive",apkfile,true); // intent.setDataAndType(uriForFile, // "application/vnd.android.package-archive"); mContext.startActivity(intent); downloadDialog.dismiss(); } //升級對話方塊 public void showDialog(final String downApkUrl,String message) { AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setTitle("版本升級"). setIcon(R.mipmap.phone_icon). // 設定提示框的圖示 setMessage("發現新版本+\n"+message).// 設定要顯示的資訊 setPositiveButton("確定", new DialogInterface.OnClickListener() {// 設定確定按鈕 @Override public void onClick(DialogInterface dialog, int which) { startUpload(downApkUrl);//下載最新的版本程式 } }).setNegativeButton("取消", null);//設定取消按鈕,null是什麼都不做,並關閉對話方塊 AlertDialog alertDialog = builder.create(); // 顯示對話方塊 alertDialog.show(); } private void startUpload(String downApkUrl) { AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setTitle("檔案下載"); final LayoutInflater inflater = LayoutInflater.from(mContext); View v = inflater.inflate(R.layout.progress, null); mProgress = (ProgressBar) v.findViewById(R.id.progress); tvProgress = (TextView) v.findViewById(R.id.tv_progress); builder.setView(v); builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); interceptFlag = true; } }); downloadDialog = builder.create(); downloadDialog.show(); loadApkUrl = downApkUrl; DownApk(); } //這裡我是用的子執行緒,這裡大家根據自己需要 public void DownApk() { Thread thread=new Thread(new Runnable() { @Override public void run() { try { URL url = new URL(loadApkUrl); 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(); } String apkFile = saveFileName; File ApkFile = new File(apkFile); 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); // 更新進度 mHandler.sendEmptyMessage(DOWN_UPDATE); if (numread <= 0) { // 下載完成通知安裝 mHandler.sendEmptyMessage(DOWN_OVER); break; } fos.write(buf, 0, numread); } while (!interceptFlag);// 點選取消就停止下載. } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); thread.start(); } }
4.progress.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<ProgressBar
android:id="@+id/progress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"
/>
<TextView
android:id="@+id/tv_progress"
android:layout_width="match_parent"
android:gravity="right"
android:text="0%"
android:layout_height="wrap_content" />
</LinearLayout>
/**
* android7.0 安裝Apk 必須要加臨時許可權
* @param context
* @param intent
* @param type
* @param file
* @param writeAble 是讀還是寫,一般安裝都是以讀形式,預設為true
*/
public static void setIntentDataAndType(Context context,
Intent intent,
String type,
File file,
boolean writeAble) {
if (Build.VERSION.SDK_INT >= 24) {
intent.setDataAndType(getUriForFile(context, file), type);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (writeAble) {
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
} else {
intent.setDataAndType(Uri.fromFile(file), type);
}
end:注意:8.0機型如發現無法安裝,請在manifest新增
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />