就目前来看,基本你手机里安装的所有APP,基本都有自动检查更新。那么这个功能怎么实现呢?本人小白,最近琢磨了一下思路,经过实践,确实可以,现在为大家分享我的过程。希望可以帮到你。
一.思路
我们先屡屡思路:既然要自动检查更新,那么我们可以将检查逻辑放到首页或者欢迎页,在这里我们要进行一个比较。比较我们已经安装的版本和服务器获取的版本。比之大,则提示更新,反之,不提示。比较完了,也就要去下载文件,也就是我们放在服务器的apk包。 下载完成后,就要去安装。这就是我的一个逻辑。
二.步骤
1.先获取已经安装的版本号:
获取本地版本号:
private void getAppVersion() {
PackageManager manager =this.getPackageManager();//得到packManager对象
try {
//得到PackageInfo对象,封装了一些软件包的信息在里面
packageInfo = manager.getPackageInfo(this.getPackageName(), 0);
int appersionCode =packageInfo.versionCode;//获取清单文件中vertsionCode节点的值
Toast.makeText(this, "当前版本为:"+appersionCode+"版本名称为:"+packageInfo.versionName, Toast.LENGTH_SHORT).show();
}catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
我这里的参数loadtxt是我自己写的一个json文件,里面包含版本号,下载路劲等字段。这个可以自己设置。
2.获取服务器版本号:
private static void getServiceAppVersion(final String loadtxt) {
new Thread(new Runnable() {
@Override
public void run() {
Request request=new Request.Builder().url(loadtxt).build();
OkHttpClient okHttpClient = new OkHttpClient();
try { Response response = okHttpClient.newCall(request).execute();
if(response.isSuccessful()){ String loadString = response.body().string();
Log.d("TAG", "body: "+loadString);
JSONObject jsonObject = new JSONObject(loadString);
Log.i("TAG", "jsonObject: "+jsonObject);
loadUrl = jsonObject.optString("loadUrl", null);
versionName = jsonObject.optString("versionName", null);
versionCode = jsonObject.optInt("versionCode",0);
versionPackageName = jsonObject.optString("versionPackageName", null);
Log.i("TAG", "请求的值:"+loadUrl+","+versionCode+","+versionName+","+versionPackageName); UpdateBean updateBean = new UpdateBean(); updateBean.setLoadUrl(loadUrl); updateBean.setVersionName(versionName);
updateBean.setVersionCode(versionCode); updateBean.setVersionPackageName(versionPackageName);
Log.i("TAG","updateBean:"+updateBean.getLoadUrl()+","+updateBean.getVersionCode()+","+updateBe an.getVersionPackageName()+","+updateBean.getVersionName());
}else{ Log.d("TAG", "run: 请求失败");
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
}).start();
}
3.进行比较:
private void getJudgeVersion() {
//如果大于,则需要更新,反之不需要
Log.i("TAG", "getJudgeVersion: "+versionCode+","+packageInfo.versionCode);
if(versionCode>packageInfo.versionCode){
new AlertDialog.Builder(this)
.setTitle("更新提示")
.setMessage("发现新版本:" +versionName +"\n" +"当前版本为:" +packageInfo.versionName +"\n" +"是否更新?")
.setPositiveButton("更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DownloadAppUtils.downloadForAutoInstall(MainActivity.this,loadUrl,"XXXX.apk","xxxx");
}
})
.setNegativeButton("暂不", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}else{
Toast.makeText(this, "您当前已是最新版本", Toast.LENGTH_SHORT).show();
}
}
到这里我们已经比较完成了,那我们去下载吧。
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import java.io.File;
public class DownloadAppUtils {
private static final StringTAG=DownloadAppUtils.class.getSimpleName();
//下载更新APK,下载任务对应的ID
public static long downloadUpdateApkId=-1;
//下载Apk 文件路径
public static StringdownloadUpdateApkFilePath;
/**
* 通过浏览器下载APk.
*/
public static void downloadForWebView(Context context,String url){
Uri uri = Uri.parse(url);
Intent intent=new Intent(Intent.ACTION_VIEW,uri);
context.startActivity(intent);
}
public static void downloadForAutoInstall(Context context,String url,String fileName,String title){
if(TextUtils.isEmpty(url)){
return;
}
try {
Uri uri = Uri.parse(url);
DownloadManager downloadManager=(DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request=new DownloadManager.Request(uri);
//在通知栏显示
request.setVisibleInDownloadsUi(true);
request.setTitle(title);
String filePath=null;
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
filePath=Environment.getExternalStorageDirectory().getAbsolutePath();
}else{
Log.i("TAG", "downloadForAutoInstall: ");
return;
}
downloadUpdateApkFilePath=filePath+ File.separator+fileName;
//若存在,则删除
deleteFile(downloadUpdateApkFilePath);
Uri fileUri=Uri.parse("file://"+downloadUpdateApkFilePath);
request.setDestinationUri(fileUri);
downloadUpdateApkId=downloadManager.enqueue(request);
}catch (Exception e){
e.printStackTrace();
downloadForWebView(context,url);
}
}
private static boolean deleteFile(String fileStr){
File file =new File(fileStr);
return file.delete();
}
}
到这里 我们下载完成了,但是还没有结束。
下面提几个点:
想要让APP自行安装,那么我们需要在适当的位置进行动态授权,而不能光靠静态权限。
读写权限以及下载等权限,还有自己别忘了网络权限。
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
<uses-permission android:name="android.permission.INTERNET" />
这里onCreate方法上面依旧是为了动态权限,而下面则是为了取消严格模式,这样我们下载完成后便可以跳转到安装界面了。
package com.example.testupdateapp.utils;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
public class UpdateAppReceiverextends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//处理下载完成
Cursor c=null;
if(DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())){
if(DownloadAppUtils.downloadUpdateApkId>=0){
long downloadId=DownloadAppUtils.downloadUpdateApkId;
DownloadManager.Query query =new DownloadManager.Query();
query.setFilterById(downloadId);
DownloadManager downloadManager=(DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
c=downloadManager.query(query);
if(c.moveToFirst()){
int status=c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
if(status==DownloadManager.STATUS_FAILED){
downloadManager.remove(downloadId);
}else if(status==DownloadManager.STATUS_SUCCESSFUL){
if(DownloadAppUtils.downloadUpdateApkFilePath!=null){
Intent i =new Intent(Intent.ACTION_VIEW);
i.setDataAndType(Uri.parse("file://"+DownloadAppUtils.downloadUpdateApkFilePath),"application/vnd.android.package-archive");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
c.close();
}
}
}
}
到这里 我们便安装成功了。不过还需要到我们的清单文件中去配置一下。
<receiver
android:name=".utils.UpdateAppReceiver"
android:enabled="true"
android:exported="true">
<action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
<action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED" />
</receiver>
好了,到这里,也就结束了~
大家赶紧试试吧~