服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - 详解Android app自动更新总结(已适配9.0)

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

2022-10-14 13:53_老李 Android

这篇文章主要介绍了详解Android app自动更新总结(已适配9.0),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

1.配置:

1.1 AndroidManifest.xml中添加权限和FileProvider:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
<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):

?
1
2
3
<paths>
 <external-path path="." name="external_storage_root" />
</paths>

1.3 (app的)build.gradle:

?
1
2
3
4
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 核心代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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:

?
1
2
3
4
5
6
public interface DataRequestListener<T> {
 //请求成功
 void success(T data);
 //请求失败
 void fail(String msg);
}

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

2.3 AppUpdateUtil:

?
1
2
3
4
5
6
7
8
9
/**
 * 获取App版本码
 *
 * @param context 上下文
 * @return App版本码
 */
public static int getAppVersionCode(Context context) {
 return getAppVersionCode(context, context.getPackageName());
}

2.4 IntentUtil:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
 * 将文件转换成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)

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

原文链接:https://juejin.im/post/5cc3b00a518825253a16af2a

延伸 · 阅读

精彩推荐