欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

详解Android app自动更新总结(已适配9.0)

程序员文章站 2022-06-21 09:55:06
1.配置: 1.1 androidmanifest.xml中添加权限和fileprovider:

1.配置:

1.1 androidmanifest.xml中添加权限和fileprovider:

 <uses-permission android:name="android.permission.internet"/>
 <uses-permission android:name="android.permission.read_external_storage"/>
 <uses-permission android:name="android.permission.write_external_storage"/>
 <uses-permission android:name="android.permission.request_install_packages" />
  <provider
   android:name="androidx.core.content.fileprovider"
   android:authorities="com.fengzhi.wuyemanagement.fileprovider"
   android:granturipermissions="true"
   android:exported="false">
   <meta-data
    android:name="android.support.file_provider_paths"
    android:resource="@xml/file_paths" />
  </provider>

1.2 新建文件(路径:res\xml\file_paths.xml):

<paths>
 <external-path path="." name="external_storage_root" />
</paths>

1.3 (app的)build.gradle:

 implementation "com.lzy.net:okgo:3.0.4"//okgo 网络请求
 implementation 'com.google.code.gson:gson:2.8.2'//gson
 implementation "org.permissionsdispatcher:permissionsdispatcher:4.3.1"//权限
 annotationprocessor "org.permissionsdispatcher:permissionsdispatcher-processor:4.3.1"//权限

2.这里以点击按钮进行更新为例:

 2.1 核心代码:

 private int version;
 /* 更新进度条 */
 private progressbar mprogress;
 private alertdialog mdownloaddialog;
 
--------------------------------------------------------------------------------------------------------------------
 
 //点击按钮,检查权限,,,检查更新的方法
 @needspermission({manifest.permission.read_external_storage,
   manifest.permission.write_external_storage,
   manifest.permission.request_install_packages})
 protected void checkupdate() {
  showloadingdialog("检测更新中...");
  version = appupdateutil.getappversioncode(this);//检查当前版本号
//  调用方法,,,接口的具体实现,接收传过来的参数,再调自己的方法,
  requestappupdate(version, new datarequestlistener<updateappbean>() {
   @override
   public void success(updateappbean data) {
//    返回的json,getstatus为0时,去下载apk文件,这里是下载apk文件的方法
    updateapp(data.getdata().getapk_url());
   }

   @override
   public void fail(string msg) {
//    返回的json,getstatus为1时,提示:"已是最新版本!"
    stoast(msg);
    dismissloadingdialog();
   }
  });
 }

 //检查版本号,第一次请求(post),,,updateappbean根据服务器返回生成
 private void requestappupdate(int version, final datarequestlistener<updateappbean> listener) {
  okgo.<string>post(const.host_url + const.updateapp).params("version", version).execute(new stringcallback() {
   @override
   public void onsuccess(response<string> response) {
    gson gson = new gson();
    updateappbean updateappbean = gson.fromjson(response.body(), updateappbean.class);
    if (updateappbean.getstatus() == 0) {
     listener.success(updateappbean);
    } else {
     listener.fail(updateappbean.getmsg());
    }
   }

   @override
   public void onerror(response<string> response) {
    listener.fail("服务器连接失败");
    dismissloadingdialog();
   }
  });
 }

 //如果有新版本,提示有新的版本,然后下载apk文件
 private void updateapp(string apk_url) {
  dismissloadingdialog();
  dialogutils.getinstance().showdialog(this, "发现新的版本,是否下载更新?",
    new dialogutils.dialoglistener() {
   @override
   public void positivebutton() {
    downloadapp(apk_url);
   }
  });
 }

 //下载apk文件并跳转(第二次请求,get)
 private void downloadapp(string apk_url) {
  okgo.<file>get(apk_url).tag(this).execute(new filecallback() {
   @override
   public void onsuccess(response<file> response) {
    string filepath = response.body().getabsolutepath();
    intent intent = intentutil.getinstallappintent(mcontext, filepath);
//    测试过这里必须用startactivity,不能用stratactivityforresult
    mcontext.startactivity(intent);
    dismissloadingdialog();
    mdownloaddialog.dismiss();
    mdownloaddialog=null;
   }

   @override
   public void downloadprogress(progress progress) {
//      showdownloaddialog();
//      mprogress.setprogress((int) (progress.fraction * 100));
    if (mdownloaddialog == null) {
     // 构造软件下载对话框
     alertdialog.builder builder = new alertdialog.builder(mcontext);
     builder.settitle("正在更新");
     // 给下载对话框增加进度条
     final layoutinflater inflater = layoutinflater.from(mcontext);
     view v = inflater.inflate(r.layout.item_progress, null);
     mprogress = (progressbar) v.findviewbyid(r.id.update_progress);
     builder.setview(v);
     mdownloaddialog = builder.create();
     mdownloaddialog.setcancelable(false);
     mdownloaddialog.show();
    }
    mprogress.setprogress((int) (progress.fraction * 100));
   }
  });
 }

2.2 datarequestlistener:

public interface datarequestlistener<t> {
 //请求成功
 void success(t data);
 //请求失败
 void fail(string msg);
}

接下来是工具类,来自github,参考, https://github.com/vondear/rxtool

2.3 appupdateutil:

 /**
  * 获取app版本码
  *
  * @param context 上下文
  * @return app版本码
  */
 public static int getappversioncode(context context) {
  return getappversioncode(context, context.getpackagename());
 }

2.4 intentutil:

public class intentutil {

 /**
  * 获取安装app(支持7.0)的意图
  *
  * @param context
  * @param filepath
  * @return
  */
 public static intent getinstallappintent(context context, string filepath) {
  //apk文件的本地路径
  file apkfile = new file(filepath);
  if (!apkfile.exists()) {
   return null;
  }
  intent intent = new intent(intent.action_view);
  uri contenturi = fileutil.geturiforfile(context, apkfile);
  intent.setflags(intent.flag_activity_new_task);
  if (build.version.sdk_int >= build.version_codes.n) {
   intent.addflags(intent.flag_grant_read_uri_permission | intent.flag_grant_write_uri_permission);
  }
  intent.setdataandtype(contenturi, "application/vnd.android.package-archive");
  return intent;
 }

2.5 fileutil:

 /**
  * 将文件转换成uri(支持7.0)
  *
  * @param mcontext
  * @param file
  * @return
  */
 public static uri geturiforfile(context mcontext, file file) {
  uri fileuri = null;
  if (build.version.sdk_int >= 24) {
   fileuri = fileprovider.geturiforfile(mcontext, mcontext.getpackagename() + ".fileprovider", file);
  } else {
   fileuri = uri.fromfile(file);
  }
  return fileuri;
 }

3.遇到的问题

9.0手机authorities配置出错,导致无法安装, 解决办法:

详解Android app自动更新总结(已适配9.0)

1.项目中使用了androidx,androidmanifest.xml的配置中就必须使用androidx的fileprovider

2.这里的authorities与fileutil.java中的要一样,我就是字母p大写了导致错误

详解Android app自动更新总结(已适配9.0)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。