安卓app应用更新全流程如下
管理员登录后台系统,从浏览器上通过前端将apk以及版本号和更新说明等信息上传到后台。
后台提供app版本的管理的上传接口和增删改查的接口以及检测最新版本的接口。
app在启动后会首先调用检测最新版本的接口,获得最新版本的相关信息,如果最新版本的版本号大于当前应用的版本号则提示是否更新,点击更新后则会后后台提供的下载接口去下载最新的安装包并安装。
注:
博客主页:
https://blog.csdn.net/badao_liumang_qizhi
关注公众号
霸道的程序猿
获取编程相关电子书、教程推送与免费下载。
新建一个AndroID项目,这里叫AppUpdateDemo
然后打开build.gradle,添加gson和okhttp的依赖
implementation 'com.Google.code.gson:gson:2.8.6' implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
添加位置如下
然后打开AndroIDManifest.xml添加相关权限
<uses-permission androID:name="androID.permission.INTERNET" /> <uses-permission androID:name="androID.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission androID:name="androID.permission.READ_EXTERNAL_STORAGE" /> <uses-permission androID:name="androID.permission.ACCESS_NETWORK_STATE" /> <!-- d出系统对话框 因为要在Service中d出对话框,故添加该权限,使得对话框独立运行,不依赖某个Activity --> <uses-permission androID:name="androID.permission.SYstem_ALERT_WINDOW" /> <!--安装文件--> <uses-permission androID:name="androID.permission.REQUEST_INSTALL_PACKAGES"/>
添加位置如下
因为在下载完apk之后需要打开下载的apk安装包进而调出安装,而在安卓7.0以上禁止在应用外部公开file://URL
所以需要在AndroIDManifest.xml中做如下配置
<!-- 在安卓7.0以上禁止在应用外部公开 file://URI --> <provIDer androID:name="androIDx.core.content.fileProvIDer" androID:authoritIEs="com.badao.appupdatedemo.fileProvIDer" androID:exported="false" androID:grantUriPermissions="true"> <Meta-data androID:name="androID.support.file_PROVIDER_PATHS" androID:resource="@xml/file_path" /> <!-- 上面的resource="xxx"指的是一个文件,file_path是文件名 --> </provIDer>
配置位置如下
一定要注意这里代码中的包名要修改为跟自己的包名一致
然后上面的配置会指向一个res下xml下的file_path.xml的路径,此时在AndroID Studio中会报红色提示,将鼠标放在红色提示上,
根据提示新建此文件
回车之后,点击OK即可
建立成功之后的路径为
建立成功之后将其代码修改为
<?xml version="1.0" enCoding="utf-8"?><paths xmlns:androID="http://schemas.androID.com/apk/res/androID"> <external-path name="install_eric" path="."/> <root-path name="root_path" path="."/></paths>
这样在下载安装包之后就能调起安装
然后在包下新建config文件夹,然后新建一个UpdateConfig类
package com.badao.appupdatedemo.config;public class UpdateConfig { //文件存在且完整 public static final int file_EXIST_INTACT = 1; //文件不存在 public static final int file_NOT_EXIST = 2; //文件不完整 public static final int file_NOT_INTACT = 3; //文件不完整 删除文件异常 public static final int file_DELETE_ERROR = 4; //获取版本信息异常 public static final int CLIENT_INFO_ERROR = 5; //需要d出哪个对话框 public static final int DIALOG_MUST = 6; public static final int DIALOG_CAN = 7; //下载异常 public static final int DOWNLOAD_ERROR = 8; //安装异常 public static final int INSTALL_ERROR = 9;}
再新建一个update目录,此目录下新建三个类
第一个类是UpdateCheck
package com.badao.appupdatedemo.update;import androID.content.Context;import androID.net.ConnectivityManager;import androID.net.NetworkInfo;import androID.os.Binder;import androID.os.Build;import androID.provIDer.Settings;import androID.text.TextUtils;import androID.util.Log;import com.badao.appupdatedemo.bean.UpdateBean;import com.Google.gson.Gson;import java.io.IOException;import java.lang.reflect.FIEld;import java.lang.reflect.Method;import okhttp3.Call;import okhttp3.Callback;import okhttp3.OkhttpClIEnt;import okhttp3.Request;import okhttp3.Response;public class UpdateCheck { /** * 当前已连接的网络是否可用 * @param context * @return */ public static boolean isNetWorkAvailable(Context context) { if (context != null) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager != null) { NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetworkInfo.isConnected()){ return activeNetworkInfo.isAvailable(); }else{ return false; } } else { return false; } } return false; } /** * 网络是否已经连接 * @param context * @return */ public static boolean isNetWorkConnected(Context context){ if (context!=null){ ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivityManager!=null){ NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo.isConnected(); }else { return false; } } return false; } /** * 检查版本 后台需要传的是版本名和包名, 可以根据自己需求更改 * @param clIEnt * @param url * @param packagename * @param result */ public static voID checkVersion(OkhttpClIEnt clIEnt, String url, String versionname, String packagename, CheckVersionResult result){ if (TextUtils.isEmpty(url)){ result.fail(-1); }else { Log.i("EricLog", "url = \n" + url); Request.Builder request = new Request.Builder(); request.url(url); clIEnt.newCall(request.get().build()).enqueue(new Callback() { @OverrIDe public voID onFailure(Call call, IOException e) { result.error(e); } @OverrIDe public voID onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()){ Gson gson = new Gson(); String s = response.body().string(); //UpdateBean实体类, 根据自己需求写 UpdateBean info = gson.fromJson(s, UpdateBean.class); //后台只给返回在服务器磁盘上的地址 String oldUrl = info.getData().getDownloadlink(); Log.i("oldUrl", "oldUrl = \n" + oldUrl); //这里将下载apk的地址适配为自己的下载地址 String newUrl = "http://自己服务器的ip:8888/system/file/download?filename="+oldUrl; Log.i("newUrl", "newUrl = \n" + newUrl); info.getData().setDownloadlink(newUrl); result.success(info); if (!call.isCanceled()){ call.cancel(); } }else { result.fail(response.code()); if (!call.isCanceled()) { call.cancel(); } } } }); } } /** * 检查悬浮窗权限 * @param context * @return */ public static boolean checkfloatPermission(Context context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) return true; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { try { Class cls = Class.forname("androID.content.Context"); FIEld declaredFIEld = cls.getDeclaredFIEld("APP_OPS_SERVICE"); declaredFIEld.setAccessible(true); Object obj = declaredFIEld.get(cls); if (!(obj instanceof String)) { return false; } String str2 = (String) obj; obj = cls.getmethod("getSystemService", String.class).invoke(context, str2); cls = Class.forname("androID.app.AppOpsManager"); FIEld declaredFIEld2 = cls.getDeclaredFIEld("MODE_ALLOWED"); declaredFIEld2.setAccessible(true); Method checkOp = cls.getmethod("checkOp", Integer.TYPE, Integer.TYPE, String.class); int result = (Integer) checkOp.invoke(obj, 24, Binder.getCallingUID(), context.getPackagename()); return result == declaredFIEld2.getInt(cls); } catch (Exception e) { return false; } } else { return Settings.canDrawOverlays(context); } } public interface CheckVersionResult{ //UpdateBean是实体类 自己替换就行 voID success(UpdateBean info); voID fail(int code); voID error(Throwable throwable); } }
此类主要是一些工具类方法。
使用时需要将此类中下载apk的地址修改为自己后台服务器的下载地址
这里需要下载地址进行拼接并重新赋值的原因是,后台在上传apk时调用的是通用的apk上传接口
返回的是在服务器上的完整路径,而在下载时调用的是通用的文件下载接口,传递的是文件在服务器上的
全路径。
第二个类是UpdateDialog
package com.badao.appupdatedemo.update;import androID.app.AlertDialog;import androID.app.Dialog;import androID.app.ProgressDialog;import androID.content.Context;import androID.content.DialogInterface;import androID.os.Build;import androID.vIEw.WindowManager;public class UpdateDialog { /** * 强制更新对话框 * @param context * @param msg * @param Listener * @return */ public static Dialog mustUpdate(Context context, String msg, DialogInterface.OnClickListener Listener){ AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("版本更新"); builder.setMessage(msg); builder.setCancelable(false); builder.setPositivebutton("更新", Listener); return builder.create(); } /** * 可以更新对话框 * @param context * @param msg * @param Listener * @param cancel * @return */ public static Dialog canUpdate(Context context, String msg, DialogInterface.OnClickListener Listener, DialogInterface.OnCancelListener cancel){ AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("版本更新"); builder.setMessage(msg); builder.setCancelable(false); builder.setPositivebutton("更新", Listener); builder.setNegativebutton("暂不更新", Listener); builder.setonCancelListener(cancel); return builder.create(); } /** * 版本获取异常对话框 * @param context * @param msg * @param Listener * @return */ public static Dialog errorDialog(Context context, String msg, DialogInterface.OnClickListener Listener){ AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("版本更新"); builder.setMessage(msg); builder.setCancelable(false); builder.setNegativebutton("确定", Listener); return builder.create(); } /** * 更新进度对话框 * @param context * @return */ public static ProgressDialog durationDialog(Context context){ ProgressDialog dialog = new ProgressDialog(context); dialog.setTitle("版本更新"); dialog.setProgressstyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setCancelable(false); return dialog; } /** * 设置系统对话框 * @param dialog */ public static voID setType(Dialog dialog){ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { dialog.getwindow().setType(WindowManager.LayoutParams.TYPE_APPliCATION_OVERLAY); }else { dialog.getwindow().setType(WindowManager.LayoutParams.TYPE_SYstem_ALERT); } }}
此类主要是声明一些d窗。
第三个类是Updatefile
package com.badao.appupdatedemo.update;import androID.content.Context;import androID.content.Intent;import androID.net.Uri;import androID.os.AsyncTask;import androID.os.Build;import androID.os.Handler;import androID.util.Log;import androIDx.core.content.fileProvIDer;import com.badao.appupdatedemo.BuildConfig;import com.badao.appupdatedemo.config.UpdateConfig;import java.io.file;import java.io.fileOutputStream;import java.io.IOException;import java.io.inputStream;import okhttp3.OkhttpClIEnt;import okhttp3.Request;import okhttp3.Response;public class Updatefile { //异步校验网络文件 如果后台没有把文件长度传你可以使用这个判断 public static class Checkfile extends AsyncTask<String, Integer, VoID> { private file file; private String fileUrl; private Handler handler; public Checkfile(file file, String fileUrl, Handler handler){ this.file = file; Log.i("Checkfile-file","file="+file.toString()); this.fileUrl = fileUrl; Log.i("Checkfile-fileUrl","fileUrl="+fileUrl.toString()); this.handler = handler; } @OverrIDe protected VoID doInBackground(String... strings) { if (file.exists()){ if (verifyfile(fileUrl,file)){ //如果文件完整 handler.sendEmptyMessage(UpdateConfig.file_EXIST_INTACT); }else { //如果文件不完整则先删除现有文件,然后下载文件 if (!file.delete()) { handler.sendEmptyMessage(UpdateConfig.file_DELETE_ERROR); return null; } handler.sendEmptyMessage(UpdateConfig.file_NOT_INTACT); } }else { handler.sendEmptyMessage(UpdateConfig.file_NOT_EXIST); } return null; } } /** * 校验网络文件 * @param mfile * @param fileUrl * @param handler */ public static voID checkfile(file mfile, String fileUrl, Handler handler) { Log.i("EricLog", "校验文件"); if (mfile.exists()){ if (verifyfile(fileUrl,mfile)){ //如果文件完整 handler.sendEmptyMessage(UpdateConfig.file_EXIST_INTACT); }else { //如果文件不完整则先删除现有文件,然后下载文件 if (!mfile.delete()) { handler.sendEmptyMessage(UpdateConfig.file_DELETE_ERROR); return; } handler.sendEmptyMessage(UpdateConfig.file_NOT_INTACT); } }else { handler.sendEmptyMessage(UpdateConfig.file_NOT_EXIST); } } /** * 校验文件是否完整 * @param urlLoadpath * @param file * @return */ private static boolean verifyfile(String urlLoadpath, file file){ long length = file.length();//已下载的文件长度 long realLength = getfileLength(urlLoadpath);//网络获取的文件长度 Log.e("EricLog", "下载长度:" +length +"\t\t文件长度:" +realLength); if (length != 0){ if (realLength != 0 && (realLength == length)){ return true; } } return false; } /** * 获取需要下载的文件长度 * @param url * @return */ private static long getfileLength(String url) { OkhttpClIEnt clIEnt = new OkhttpClIEnt(); Request request = new Request.Builder() .url(url) .build(); Response response; try { response = clIEnt.newCall(request).execute(); if (response.isSuccessful()){ long length = response.body().contentLength(); response.body().close(); return length; } } catch (IOException e) { e.printstacktrace(); } return 0; } //安装 public static voID installApp(file file, Context context, Handler handler) { if (!file.exists()) { return; } // 跳转到新版本应用安装页面 try { Intent intent = new Intent(Intent.ACTION_VIEW); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N){ intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); Uri uri = fileProvIDer.getUriForfile(context, BuildConfig.APPliCATION_ID+ ".fileProvIDer",file); intent.setDataAndType(uri, "application/vnd.androID.package-archive"); }else { intent.setDataAndType(Uri.fromfile(file), "application/vnd.androID.package-archive"); } context.startActivity(intent); }catch (Throwable throwable){ Log.e("EricLog", "Error = " +throwable.getMessage()); handler.sendEmptyMessage(UpdateConfig.INSTALL_ERROR); } } /** * 异步网络文件下载并保存 * */ public static class DownloadAsync extends AsyncTask<String,Integer,Integer> { private static final int DOWNLOAD_SUCCESS = 1; private static final int DOWNLOAD_FAIL = 2; private DownloadListener Listener; private int lastProgress; private file file; public DownloadAsync(file file, DownloadListener Listener){ this.file = file; this.Listener = Listener; } public interface DownloadListener{ voID onProgress(int progress); voID onSuccess(); voID onFail(); } @OverrIDe protected Integer doInBackground(String... strings) { inputStream inputStream = null; fileOutputStream fileOutputStream = null; long contentLength = getfileLength(strings[0]); try { OkhttpClIEnt clIEnt = new OkhttpClIEnt(); Request request = new Request.Builder() .url(strings[0]) .build(); Response response = clIEnt.newCall(request).execute(); if (response.code() == 200) { inputStream = response.body().byteStream(); fileOutputStream = new fileOutputStream(file); byte[] b = new byte[1024]; int total = 0; int len; while ((len = inputStream.read(b)) != -1) { total += len; fileOutputStream.write(b, 0, len); //百分比的计算在这里 float pressent = (float) total / contentLength * 100; int progress = (int) pressent; publishProgress(progress); } response.body().close(); return DOWNLOAD_SUCCESS; }else { return DOWNLOAD_FAIL; } } catch (IOException e) { e.printstacktrace(); } finally { try { if (inputStream != null) { inputStream.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } } catch (IOException e) { e.printstacktrace(); } } return DOWNLOAD_FAIL; } @OverrIDe protected voID onProgressUpdate(Integer... values) { int progress = values[0]; if (progress > lastProgress){ Listener.onProgress(progress); lastProgress = progress; } } @OverrIDe protected voID onPostExecute(Integer integer) { switch (integer){ case DOWNLOAD_SUCCESS: Listener.onSuccess(); break; case DOWNLOAD_FAIL: Listener.onFail(); break; default: break; } } }}
此类主要是用于校验文件、获取文件大小和下载与安装文件的一些方法
新建完这三个工具类之后,再在包下新建一个service目录,在此目录下新建一个Service
然后修改名字为UpdateService
点击Finish之后,会在AndroIDManifest.xml中自动添加一个service
<service androID:name=".service.UpdateService" androID:enabled="true" androID:exported="true"></service>
然后修改UpdateService的代码
package com.badao.appupdatedemo.service;import androID.annotation.Suppresslint;import androID.app.Dialog;import androID.app.ProgressDialog;import androID.app.Service;import androID.content.Context;import androID.content.DialogInterface;import androID.content.Intent;import androID.content.pm.PackageInfo;import androID.content.pm.PackageManager;import androID.os.Environment;import androID.os.Handler;import androID.os.IBinder;import androID.os.Message;import androID.text.TextUtils;import androID.util.Log;import androIDx.annotation.NonNull;import com.badao.appupdatedemo.bean.UpdateBean;import com.badao.appupdatedemo.config.UpdateConfig;import com.badao.appupdatedemo.update.UpdateCheck;import com.badao.appupdatedemo.update.UpdateDialog;import com.badao.appupdatedemo.update.Updatefile;import java.io.file;import java.io.IOException;import java.util.concurrent.TimeUnit;import okhttp3.OkhttpClIEnt;public class UpdateService extends Service { public static boolean isRunning = false; public static String checkUrl = "http://你自己服务器的地址:8888/fzyscontrol/sys/version/getLastestVersion"; //当前版本 private int versionCode = -1; //错误信息 private String error_msg = ""; //更新地址 private String updateUrl = ""; //更新描述 private String description = ""; //文件路径 private String filePath = ""; //文件名称 private String appname = ""; //目标文件 private file targetfile; private static OkhttpClIEnt clIEnt = getClIEnt(); private Dialog mDialog; private ProgressDialog mProgressDialog; @Suppresslint("HandlerLeak") private Handler handler = new Handler() { @OverrIDe public voID handleMessage(@NonNull Message msg) { super.handleMessage(msg); int code = msg.what; switch (code) { case UpdateConfig.file_EXIST_INTACT: Log.i("EricLog", "文件完整 需要安装"); Updatefile.installApp(targetfile, getApplicationContext(), handler); break; case UpdateConfig.file_NOT_EXIST: Log.i("EricLog", "文件不存在"); mProgressDialog = UpdateDialog.durationDialog(getApplicationContext()); //设置为系统对话框 UpdateDialog.setType(mProgressDialog); mProgressDialog.show(); Updatefile.DownloadAsync dFne = new Updatefile.DownloadAsync(targetfile, Listener); dFne.execute(updateUrl); break; case UpdateConfig.file_DELETE_ERROR: Log.i("EricLog", "文件删除异常"); error_msg = "文件删除出错了"; showDialog(DialogType.ERROR); break; case UpdateConfig.file_NOT_INTACT: Log.i("EricLog", "文件不完整"); mProgressDialog = UpdateDialog.durationDialog(getApplicationContext()); UpdateDialog.setType(mProgressDialog); mProgressDialog.show(); Updatefile.DownloadAsync dFni = new Updatefile.DownloadAsync(targetfile, Listener); dFni.execute(updateUrl); break; case UpdateConfig.DIALOG_MUST: Log.i("EricLog", "d出必须更新对话框"); showDialog(DialogType.MUST); break; case UpdateConfig.DIALOG_CAN: Log.i("EricLog", "d出可以更新对话框"); showDialog(DialogType.CAN); break; case UpdateConfig.CLIENT_INFO_ERROR: Log.i("EricLog", "连接异常"); error_msg = "获取版本异常,请检查网络"; showDialog(DialogType.ERROR); break; case UpdateConfig.DOWNLOAD_ERROR: Log.i("EricLog", "下载异常"); disProgress(false); error_msg = "下载出错了,请重新下载"; showDialog(DialogType.ERROR); break; case UpdateConfig.INSTALL_ERROR: Log.i("EricLog", "安装异常"); error_msg = "安装出错了,请手动安装"; showDialog(DialogType.ERROR); break; } } }; @OverrIDe public IBinder onBind(Intent intent) { return null; } @OverrIDe public voID onCreate() { super.onCreate(); Log.i("EricLog", "服务启动"); filePath = Environment.getExternalStorageDirectory() .getabsolutePath() + file.separator + "MyApp/"; Log.i("onCreate-filePath", "filePath="+filePath); } @OverrIDe public int onStartCommand(Intent intent, int flags, int startID) { if (!isRunning) { isRunning = true; versionCode = getVersionCode(getApplicationContext()); String versionname = getVersionname(getApplicationContext()); if (versionCode == -1 || TextUtils.isEmpty(versionname)){ handler.sendEmptyMessage(UpdateConfig.CLIENT_INFO_ERROR); }else { if (UpdateCheck.isNetWorkConnected(getApplicationContext()) && UpdateCheck.isNetWorkAvailable(getApplicationContext())) { UpdateCheck.checkVersion(clIEnt, checkUrl, versionname, getPackagename(), result); } else { handler.sendEmptyMessage(UpdateConfig.CLIENT_INFO_ERROR); } } } return super.onStartCommand(intent, flags, startID); } @OverrIDe public voID onDestroy() { super.onDestroy(); Log.i("EricLog", "服务销毁"); isRunning = false; } /** * 获取版本号 * @return */ public static int getVersionCode(Context context){ PackageManager manager = context.getPackageManager(); PackageInfo info; try { info = manager.getPackageInfo(context.getPackagename(), 0); return info.versionCode; } catch (PackageManager.nameNotFoundException e) { return -1; } } public static String getVersionname(Context context){ PackageManager manager = context.getPackageManager(); PackageInfo info; try { info = manager.getPackageInfo(context.getPackagename(), 0); return info.versionname; } catch (PackageManager.nameNotFoundException e) { return ""; } } private static OkhttpClIEnt getClIEnt(){ return new OkhttpClIEnt.Builder() .connectTimeout(15, TimeUnit.SECONDS) .build(); } /** * 检查是否需要更新 按需求写就行 */ private voID checkUpdate(UpdateBean info){ //目标版本号 int targetCode = info.getData().getVersionNum(); //是否强制更新 //int isCompulsory = info.getData().getIsCompulsory(); updateUrl = info.getData().getDownloadlink(); Log.i("updateUrl","updateUrl="+updateUrl); appname = info.getData().getAppname(); description = info.getData().getUpdateInstructions(); //这里设置下载apk后存储在本地的目标路径的文件 //这里使用的是临时文件的路径 ///data/data/com.badao.appupdatedemo/cache/badao79427110100998067.apk String mPath = filePath + appname + ".apk"; try { file tempPath = file.createTempfile("badao", ".apk"); mPath = tempPath.getabsolutePath(); } catch (IOException e) { e.printstacktrace(); } Log.i("mPath","mPath="+mPath); Log.i("EricLog", "目标文件:" + mPath); targetfile = new file(mPath); if (TextUtils.isEmpty(description)){ description = "修复了若干BUG"; } if (versionCode == targetCode){ stopSelf(); }else { handler.sendEmptyMessage(UpdateConfig.DIALOG_CAN); //其他的一些情况就按需求写吧 } } /** * 应该展示哪个对话框 * @param type */ private voID showDialog(DialogType type){ if (type == DialogType.MUST){ mDialog = UpdateDialog.mustUpdate(getApplicationContext(), description, new DialogInterface.OnClickListener() { @OverrIDe public voID onClick(DialogInterface dialog, int which) { Updatefile.Checkfile checkfile = new Updatefile.Checkfile( targetfile, updateUrl, handler); checkfile.execute(); } }); }else if (type == DialogType.CAN){ mDialog = UpdateDialog.canUpdate(getApplicationContext(), description, new DialogInterface.OnClickListener() { @OverrIDe public voID onClick(DialogInterface dialog, int which) { if (which == DialogInterface.button_POSITIVE){ Updatefile.Checkfile checkfile = new Updatefile.Checkfile( targetfile, updateUrl, handler); checkfile.execute(); }else if (which == DialogInterface.button_NEGATIVE){ dismiss(); } } }, new DialogInterface.OnCancelListener() { @OverrIDe public voID onCancel(DialogInterface dialog) { dismiss(); } }); }else if (type == DialogType.ERROR){ mDialog = UpdateDialog.errorDialog(getApplicationContext(), error_msg, new DialogInterface.OnClickListener() { @OverrIDe public voID onClick(DialogInterface dialog, int which) { dismiss(); } }); } UpdateDialog.setType(mDialog); mDialog.show(); } private voID dismiss(){ if (mDialog != null && mDialog.isShowing()){ stopSelf(); mDialog.dismiss(); } } private voID disProgress(boolean finishService){ if (finishService){ stopSelf(); } if (mProgressDialog != null && mProgressDialog.isShowing()){ mProgressDialog.dismiss(); } } private UpdateCheck.CheckVersionResult result = new UpdateCheck.CheckVersionResult() { @OverrIDe public voID success(UpdateBean info) { if (info != null && info.getData() != null) { checkUpdate(info); }else { handler.sendEmptyMessage(UpdateConfig.CLIENT_INFO_ERROR); } } @OverrIDe public voID fail(int code) { Log.e("EricLog", "Code = " + code); handler.sendEmptyMessage(UpdateConfig.CLIENT_INFO_ERROR); } @OverrIDe public voID error(Throwable throwable) { Log.e("EricLog", "Error = " +throwable.getMessage()); handler.sendEmptyMessage(UpdateConfig.CLIENT_INFO_ERROR); } }; private Updatefile.DownloadAsync.DownloadListener Listener = new Updatefile.DownloadAsync.DownloadListener() { @OverrIDe public voID onProgress(int progress) { mProgressDialog.setProgress(progress); } @OverrIDe public voID onSuccess() { disProgress(true); Updatefile.installApp(targetfile, getApplicationContext(), handler); } @OverrIDe public voID onFail() { handler.sendEmptyMessage(UpdateConfig.DOWNLOAD_ERROR); } }; /** * 要展示的对话框类型 */ public enum DialogType{ MUST, CAN, ERROR }}
将此service的checkUrl修改为自己的服务器的ip和端口
此service中用到的将服务端的远程apk下载到本地的路径为临时文件路径,在data/data/包名下cache目录下
然后还需要在包下新建bean包,在此包下新建版本更新接口返回的Json数据对应的实体类
后台检测更新的接口返回的Json数据为
然后根据此Json数据生成bean的方式参考如下
AndroIDStudio中安装GsonFormat插件并根据Json文件生成JavaBean:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/110426851
然后根据Json数据生成的UpdateBean为
package com.badao.appupdatedemo.bean;public class UpdateBean { /** * msg : *** 作成功 * code : 200 * data : {"ID":9,"appname":"测试1","versionNum":16,"downloadlink":"D://fzys/file/2020/11/30/8a4ac525-8c28-45be-834b-6db0889b7aa9.jpg","updateInstructions":"测试11122","updateTime":"2020-11-30T16:51:09.000+08:00"} */ private String msg; private int code; private DataBean data; public String getMsg() { return msg; } public voID setMsg(String msg) { this.msg = msg; } public int getCode() { return code; } public voID setCode(int code) { this.code = code; } public DataBean getData() { return data; } public voID setData(DataBean data) { this.data = data; } public static class DataBean { /** * ID : 9 * appname : 测试1 * versionNum : 16 * downloadlink : D://fzys/file/2020/11/30/8a4ac525-8c28-45be-834b-6db0889b7aa9.jpg * updateInstructions : 测试11122 * updateTime : 2020-11-30T16:51:09.000+08:00 */ private int ID; private String appname; private int versionNum; private String downloadlink; private String updateInstructions; private String updateTime; public int getID() { return ID; } public voID setID(int ID) { this.ID = ID; } public String getAppname() { return appname; } public voID setAppname(String appname) { this.appname = appname; } public int getVersionNum() { return versionNum; } public voID setVersionNum(int versionNum) { this.versionNum = versionNum; } public String getDownloadlink() { return downloadlink; } public voID setDownloadlink(String downloadlink) { this.downloadlink = downloadlink; } public String getUpdateInstructions() { return updateInstructions; } public voID setUpdateInstructions(String updateInstructions) { this.updateInstructions = updateInstructions; } public String getUpdateTime() { return updateTime; } public voID setUpdateTime(String updateTime) { this.updateTime = updateTime; } }}
最后项目的总目录为
然后打开MainActivity
在OnCreate方法中进行检测是否已经开启了悬浮窗的权限,如果已经开启了悬浮窗的权限
则直接通过
startService(new Intent(this,UpdateService.class));
的方式启动service进行是否更新的检测。
否则的话会通过
//否则跳转到开启悬浮窗的设置页面 Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M){ intent.setData(Uri.parse("package:" + getPackagename())); } //指定一个请求码,这样在重写的onActivityResult就能筛选到设置悬浮窗之后的结果 startActivityForResult(intent, 212); }
跳转到开启悬浮窗权限的页面,并指定一个请求码为212,然后在MainActivity中重写onActivityResult方法
就能通过请求码获取到跳转到开启悬浮窗页面的返回结果
如果已经开启了则直接检测更新,否则的话会d窗提示
@OverrIDe protected voID onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); //跟开启悬浮窗的请求码一致 if (requestCode == 212){ //如果开启了悬浮窗的权限 if (UpdateCheck.checkfloatPermission(this)){ //直接检测更新 startService(new Intent(this,UpdateService.class)); }else { //否则d窗提示 Toast.makeText(this, "请授予悬浮窗权限", Toast.LENGTH_SHORT).show(); } } }
MainActivity完整示例代码
package com.badao.appupdatedemo;import androIDx.annotation.Nullable;import androIDx.appcompat.app.AppCompatActivity;import androID.content.Intent;import androID.net.Uri;import androID.os.Build;import androID.os.Bundle;import androID.provIDer.Settings;import androID.Widget.Toast;import com.badao.appupdatedemo.service.UpdateService;import com.badao.appupdatedemo.update.UpdateCheck;public class MainActivity extends AppCompatActivity { @OverrIDe protected voID onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); //跟开启悬浮窗的请求码一致 if (requestCode == 212){ //如果开启了悬浮窗的权限 if (UpdateCheck.checkfloatPermission(this)){ //直接检测更新 startService(new Intent(this,UpdateService.class)); }else { //否则d窗提示 Toast.makeText(this, "请授予悬浮窗权限", Toast.LENGTH_SHORT).show(); } } } @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); //应用启动后会先走此方法 //如果已经开启了悬浮窗的权限 if (UpdateCheck.checkfloatPermission(this)) { //直接启动检测更新的service startService(new Intent(this,UpdateService.class)); }else { //否则跳转到开启悬浮窗的设置页面 Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION); if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M){ intent.setData(Uri.parse("package:" + getPackagename())); } //指定一个请求码,这样在重写的onActivityResult就能筛选到设置悬浮窗之后的结果 startActivityForResult(intent, 212); } }}
安卓端完整示例代码下载
https://download.csdn.net/download/BADAO_LIUMANG_QIZHI/13218755
然后就是搭建后台服务端。
前后端分离的方式搭建后台服务这里使用了若依的前后端分离的版的框架搭建的后台服务。
若依前后端分离版手把手教你本地搭建环境并运行项目:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/108465662
若依微服务版手把手教你本地搭建环境并运行前后端项目:
https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/109363303
上面是基于SpringBoot搭建的前后端分离的项目
下面是基于SpringCloud搭建的微服务版的项目
最终都是搭建一个前端项目和后台服务接口项目。
这里以后台微服务版的版的基础上去搭建后台接口
首先是新建通用的文件上传和下载的接口,注意此接口一定要做好权限验证与安全管理
import com.ruoyi.common.core.utils.DateUtils;import com.ruoyi.common.core.web.domain.AJAXResult;import com.ruoyi.system.utils.fileUtils;import com.ruoyi.system.utils.UploadUtil;import io.swagger.annotations.API;import io.swagger.annotations.APIOperation;import org.apache.ibatis.annotations.Param;import org.springframework.web.bind.annotation.GetMapPing;import org.springframework.web.bind.annotation.PostMapPing;import org.springframework.web.bind.annotation.RequestMapPing;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.multipart.multipartfile;import javax.servlet.http.httpServletResponse;import java.io.*;/** * 通用文件上传下载接口 * @author Chrisf */@RestController@RequestMapPing("file")@API(Tags = "文件通用上传下载")public class fileController { /** * 上传文件 * * @param file * @return */ @PostMapPing("upload") @APIOperation("上传") public AJAXResult head_portrait(@Param("file") multipartfile file) { AJAXResult AJAXResult = AJAXResult.success(); try { //文件夹路径 String path = "D://fzys/file/" + DateUtils.datePath() + "/"; fileUtils.check_folder(path); // 上传后的文件名称 String auth_file_name = UploadUtil.save_file(file, path); AJAXResult.put("code", 200); AJAXResult.put("message", "成功"); AJAXResult.put("filename", path + auth_file_name); } catch (IOException e) { AJAXResult.put("code", 400); AJAXResult.put("message", "上传失败"); AJAXResult.put("head_portrait", null); e.printstacktrace(); } return AJAXResult; } /** * 下载文件 * @param filename * @param response * @throws IOException */ @GetMapPing("download") @APIOperation("下载") public voID down_file(String filename, httpServletResponse response) throws IOException { file file = new file(filename); // 清空response response.reset(); // 设置response的header 通知浏览器 已下载的方式打开文件 防止文本图片预览 response.addheader("Content-disposition", "attachment;filename=" + new String(filename.getBytes("gbk"), "iso-8859-1")); // 转码之后下载的文件不会出现中文乱码 response.addheader("Content-Length", "" + file.length()); // 以流的形式下载文件 inputStream fis = new BufferedinputStream(new fileinputStream(filename)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); OutputStream toClIEnt = new bufferedoutputstream(response.getoutputStream()); toClIEnt.write(buffer); toClIEnt.flush(); toClIEnt.close(); }}
在这两个接口中用到的工具类方法有UploadUtil.save_file
public static String save_file(multipartfile file, String path) throws IOException { String filename=file.getoriginalfilename(); String suffix = filename.substring(filename.indexOf(".")); filename = UUID.randomUUID().toString() + suffix; file file_temp=new file(path,filename); if (!file_temp.getParentfile().exists()) { file_temp.getParentfile().mkdir(); } if (file_temp.exists()) { file_temp.delete(); } file_temp.createNewfile(); file.transferTo(file_temp); return file_temp.getname(); }
和工具类fileUtils.check_folder
public static voID check_folder(String path) { file dir = new file(path); // 判断文件夹是否存在 if (dir.isDirectory()) { } else { dir.mkdirs(); } }
以及DateUtils.datePath(),是用来生成日期文件目录的方法
/** * 日期路径 即年/月/日 如2018/08/08 */ public static final String datePath() { Date Now = new Date(); return DateFormatUtils.format(Now, "yyyy/MM/dd"); }
通用的文件上传与下载的接口做好之后就是版本检测更新的接口
首先我们需要设计一个数据库来用来存储app的版本信息
然后使用若依自带的代码生成工具去生成前后端的代码,前端代码一会也要修改,这里先找到生成的Controller
@RestController@RequestMapPing("/sys/version")@API(Tags = "APP版本管理")public class SysAppVersionController extends BaseController { @autowired private ISysAppVersionService sysAppVersionService; @autowired private SysAppVersionMapper sysAppVersionMapper; /** * 查询版本更新记录列表 * @return */ @GetMapPing("/getList") @APIOperation("查询版本更新记录列表") public tableDataInfo getList(){ startPage(); List<SysAppVersion> List = sysAppVersionService.getList(); return getDatatable(List); } /** * 新增版本更新记录 */ @PostMapPing("/add") @APIOperation("新增版本更新记录") public AJAXResult addAppVersion(@Reques@R_404_5998@ SysAppVersion sysAppVersion){ if (StringUtils.isNull(sysAppVersion.getVersionNum()) || StringUtils.isEmpty(sysAppVersion.getDownloadlink())){ return AJAXResult.error(400, "缺少必要参数"); } return sysAppVersionService.insertSysAppVersion(sysAppVersion); } /** * 修改版本更新记录 */ @PostMapPing("/edit") @APIOperation("修改版本更新记录") public AJAXResult editAppVersion(@Reques@R_404_5998@ SysAppVersion sysAppVersion){ if (sysAppVersion.getID() == null){ return AJAXResult.error(400, "缺少必要参数"); } return sysAppVersionService.updateSysAppVersion(sysAppVersion); } @GetMapPing("/getLastestVersion") @APIOperation("获取最新版本信息") public AJAXResult getLastestVersion(){ SysAppVersion sysAppVersion = sysAppVersionMapper.getLast(); return AJAXResult.success(sysAppVersion); }}
下面调用的service和mapper都是生成的对单表的进行增删改的代码
这里主要是添加一个检测版本更新的接口,即上面的获取最新版本信息。
其最终执行mapper方法为
<!--查询最新的更新记录--> <select ID="getLast" resultMap="SysAppVersionResult"> <include refID="selectSysAppVersionVo"></include> order by version_num desc limit 1 </select>
此接口从数据库中查询出来版本号最高的那条记录并将此记录的相关信息返回给app端
app获取到版本好之后跟自己的当前的版本的版本号进行对比,如果高于当前版本则提示更新。
app端版本号的设置位置在
此接口的地址就是对应安卓端UpdateService中的checkUrl的地址。
然后就是修改前端页面,将vue页面修改如下
<template> <div > <el-row :gutter="10" > <el-row > <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" >新增</el-button> </el-row> <el-table :data="tableData" :height="tableHeight" :loading="ListLoding" > <el-table-column prop="appname" label="应用名称" wIDth="180"> </el-table-column> <el-table-column prop="versionNum" label="版本号" wIDth="180"> </el-table-column> <el-table-column prop="updateTime" label="更新时间"> <template slot-scope='scope'> {{ scope.row.updateTime | dataFormat }} </template> </el-table-column> <el-table-column prop="updateInstructions" label="更新说明"> </el-table-column> <el-table-column label=" *** 作" align="center" class-name="small-padding fixed-wIDth"> <template slot-scope="scope"> <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" >修改</el-button> </template> </el-table-column> </el-table> <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="ListData" /> <!-- 添加或修改通讯录对话框 --> <el-dialog :title="Title" :visible.sync="open" wIDth="500px" append-to-body> <el-form ref="form" :model="form" :rules="rules" label-wIDth="80px"> <el-form-item label="应用名称" prop="appname" v-if="editStatus "> <el-input v-model="form.appname" placeholder="请输入应用名称" /> </el-form-item> <el-form-item label="版本号" prop="versionNum" :rules="[ { required: true, message: '版本号不能为空'}, { type: 'number', message: '版本号必须为数字值'} ]" v-if="editStatus" > <el-input v-model.number="form.versionNum" placeholder="请输入版本号" /> </el-form-item> <el-form-item label="更新说明" prop="updateInstructions"> <el-input v-model="form.updateInstructions" placeholder="请输入更新说明" /> </el-form-item> </el-form> <el-col v-if="editStatus" > <el-upload :headers="headers" :action="url" :multiple="false" :file-List="fileList" :on-remove="fileRemove" :on-success="uploadSuccess" :on-error="uploadError" :on-progress="uploadProgress" :limit="1" :on-exceed="beyond" > <el-button size="small"> 上传 <i ></i> </el-button> </el-upload> </el-col> <div slot="footer" > <el-button type="primary" @click="submitForm" :loading="btnLoding" v-show="editStatus">确 定</el-button> <el-button type="primary" @click="editsubmit" v-show="!editStatus">确 定</el-button><!--修改按钮 --> <el-button @click="cancel">取 消</el-button> </div> </el-dialog> </el-row> </div></template><script>import {upload,getList,add,edit} from "@/API/tool/edition.Js"import {getToken} from '@/utils/auth'export default { components: {}, props: {}, data() { return { //列表数据 tableData:[], // 查询参数 queryParams: { pageNum: 1, pageSize: 10, }, Title:"", // 表单参数 form: { ID:null, appname:null, downloadlink:null, updateInstructions:null, versionNum:null }, // 文件列表 fileList:[], // 表格自适应高度 tableHeight: document.body.clIEntHeight - 230, // 是否显示d出层 open:false, // 总条数 total: 0, //返回的文件url fileUrl: '', // 文件列表 // 上传按钮闸口 btnLoding:false, // 列表加载动画 ListLoding:true, // 表单校验 rules: { appname: [ { required: true, message: "应用名称不能为空", trigger: "blur" } ], updateInstructions: [ { required: true, message: "更新说明不能为空", trigger: "blur" } ], }, // 修改字段显隐 editStatus:true, // 修改ID editID:null, progess: 0, // 请求头 headers:{Authorization:"Bearer" +' ' + getToken()}, // 上传地址 url:process.env.VUE_APP_BASE_API + '/system/file/upload' }; }, watch: {}, computed: {}, methods: { ListData(){ getList(this.queryParams).then(res=>{ this.tableData = res.rows; this.total = res.total; this.ListLoding = false; }) }, // 显现新增d窗 handleAdd(){ this.Title = '新增'; this.open = true; this.editStatus = true if(this.$refs['form']){ this.$refs['form'].resetFIElds(); } this.fileList = []; this.btnLoding = false; }, // 文件上传成功 uploadSuccess(res,file,fileList){ console.log(fileList) let fileParam={ name:null, url:null } this.btnLoding = false; this.form.downloadlink = res.filename; fileParam.url =res.filename; fileParam.name =res.name; this.fileList= fileList; this.$message(res.msg); }, // 文件上传失败 uploadError(err){ this.btnLoding = false; this.$message.error(res.msg); }, // 上传中 uploadProgress(e){ this.btnLoding = true; console.log(e,'上传中') }, beyond(file, fileList){ this.$message({ message: '最多上传一个文件', type: 'warning' }); }, // 移除选择的文件 fileRemove(file, fileList) { this.btnLoding = false; console.log(file) this.fileList = []; this.form.downloadlink = null; }, // 新增 submitForm(){ this.$refs["form"].valIDate(valID => { if (valID) { // console.log(this.form.filename) if(!this.form.downloadlink){ this.$notify({ Title: '警告', message: '请上传文件后在进行提交', type: 'warning' }); }else{ add(this.form).then(res =>{ if(res.code == 200){ this.$message(res.msg); this.$refs['form'].resetFIElds(); this.fileList = []; this.open = false; this.ListData(); }else{ this.$message.error(res.msg); } }) } } }); }, // 修改 handleUpdate(row){ this.editStatus = false; this.Title = '修改'; this.open = true; this.form.updateInstructions = row.updateInstructions; this.form.ID = row.ID; }, // 修改提交 editsubmit(){ this.$refs["form"].valIDate(valID => { if (valID) { edit(this.form).then(res=>{ if(res.code == 200){ this.$message(res.msg); this.$refs['form'].resetFIElds(); this.open = false; this.ListData(); }else{ this.$message.error(res.msg); } }) } }) }, format(percentage) { return percentage === 100 ? '上传完成' : `${percentage}%`; }, cancel(){ this.open = false; this.$refs['form'].resetFIElds(); this.fileList = []; }, }, created() { this.ListData(); }, mounted() {} };</script><style lang="sCSS" scoped>.upload_Box{ min-height: 80px; padding-bottom: 10px;}.btn_Box{ margin-bottom: 20px;}</style>
除了自动生成的主要修改新增的页面,添加一个apk安装包上传的控件el-upload
调用的是前面的通用上传接口,会将apk安装包上传到服务器上并将在服务器上的地址返回,然后在点击新增页面的确认按钮后将
安装包地址一并提交到后台的新增接口,后台将其存储到数据库。
vue页面调用的Js方法为
import request from '@/utils/request' //上传文件 export function upload(query) { return request({ url: '/system/file/upload', method: 'post', data:query }) } //查询列表 export function getList(query){ return request({ url:'/fzyscontrol/sys/version/getList', method:'get', params: query }) } //新增版本记录 export function add(query){ return request({ url:'/fzyscontrol/sys/version/add', method:'post', data: query }) } // 修改版本记录 export function edit(query){ return request({ url:'/fzyscontrol/sys/version/edit', method:'post', data: query }) }
然后新增完一个版本之后就会在数据库中新增一个高版本的记录
就能实现后台将新版本的apk传递到后台,然后app在启动后会查询最新版本的信息,如果高于当前版本则会将apk下载与安装
然后点击更新,就会下载安装包并安装
总结
以上是内存溢出为你收集整理的Android+SpringBoot+Vue实现安装包前台上传,后台管理,移动端检测自动更新全部内容,希望文章能够帮你解决Android+SpringBoot+Vue实现安装包前台上传,后台管理,移动端检测自动更新所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)