利用Bmob云更新APP
程序员文章站
2024-03-24 13:17:16
...
在写自己App的时候,APP更新是非常重要的,后续版本的发布及时送到用户
效果图:
看下Bmob的后台,创建应用,配置啥的就不说了
首先我们新建表update
objectID是唯一标示,不能改变,我们根据这个ID获取APK文件的下载链接更新内容text,Code是APP版本号,服务器上的CODE号一定要比上个版本大。
流程:开启APP——检测CODE——CODE大于当前CODE执行更新——下载APK——install
获取APP版本号的工具类:
import android.content.Context;
import android.content.pm.PackageManager;
/*获取版本code和name的工具类*/
public class APKVersionCodeUtils {
/* 获取当前本地apk的版本*/
public static int getVersionCode(Context mContext) {
int versionCode = 0;
try {
//获取软件版本号,对应AndroidManifest.xml下android:versionCode
versionCode = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionCode;
}
/* 获取版本号名称*/
public static String getVerName(Context context) {
String verName = "";
try {
verName = context.getPackageManager().
getPackageInfo(context.getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return verName;
}
}
versionCode是版本号,,cersionName是版本号
调用:
int versionCode = APKVersionCodeUtils.getVersionCode(this) ;
String versionName = APKVersionCodeUtils.getVerName(this);
update.java
import cn.bmob.v3.BmobObject;
import cn.bmob.v3.datatype.BmobFile;
public class update extends BmobObject {
public BmobFile getAPK() {
return APK;
}
public void setAPK(BmobFile APK) {
this.APK = APK;
}
BmobFile APK;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
String text;
public String getCode() {
return Code;
}
public void setCode(String code) {
Code = code;
}
String Code;
public String getapkUrl(){
return APK.getFileUrl();
}
}
需要注意的是getAPKurl()这个方法是获取APK的下载链接
获取版本Code和APK链接以及text:
//查询单条数据
public void querySingleData() {
BmobQuery<update> bmobQuery = new BmobQuery<update>();
bmobQuery.getObject("MF4j000B", new QueryListener<update>() {
@Override
public void done(update object, BmobException e) {
if (e == null) {
url = object.getapkUrl();
code1 = object.getCode();
text = object.getText();
System.out.println("APK更新地址:" + url);
System.out.println("版本号:" + code1);
System.out.println("更新内容" + text);
check(code1);
} else {
Log.i("bmob图片", "失败:" + e.getMessage() + "," + e.getErrorCode());
}
}
});
}
检测版本CODE:
//判断版本大小
public void check(String code1) {
code = APKVersionCodeUtils.getVersionCode(this) ;
int i = Integer.valueOf(this.code1).intValue();
if (i > code) {
showDialog();
}
}
如果需要更新,显示Dialog给用户提示更新:
private void showDialog() {
AlertDialog dialog = new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher_background)//设置标题的图片
.setTitle("检查到新版本")//设置对话框的标题
.setMessage(text)//设置对话框的内容
//设置对话框的按钮
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(MainActivity.this, "点击了取消按钮", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
})
.setPositiveButton("更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(MainActivity.this, "点击了确定的按钮", Toast.LENGTH_SHORT).show();
//postUrl(url);
mIsCancel=false;
//展示对话框
showDownloadDialog(url);
dialog.dismiss();
}
}).create();
dialog.show();
}
/*
* 显示正在下载对话框
*/
protected void showDownloadDialog(String url) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("下载中");
View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_progress, null);
mProgressBar = (ProgressBar) view.findViewById(R.id.id_progress);
builder.setView(view);
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 隐藏当前对话框
dialog.dismiss();
// 设置下载状态为取消
mIsCancel = true;
}
});
mDownloadDialog = builder.create();
mDownloadDialog.show();
// 下载文件
downloadAPK(url);
}
downloadAPK()及install()
/*
* 开启新线程下载apk文件
*/
private void downloadAPK() {
new Thread(new Runnable() {
@Override
public void run() {
try{
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
String sdPath = Environment.getExternalStorageDirectory() + "/";
// 文件保存路径
mSavePath = sdPath + "SITdownload";
File dir = new File(mSavePath);
if (!dir.exists()){
dir.mkdir();
}
// 下载文件
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.connect();
InputStream is = conn.getInputStream();
int length = conn.getContentLength();
File apkFile = new File(mSavePath, mVersion_name);
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
byte[] buffer = new byte[1024];
while (!mIsCancel){
int numread = is.read(buffer);
count += numread;
// 计算进度条的当前位置
mProgress = (int) (((float)count/length) * 100);
// 更新进度条
mUpdateProgressHandler.sendEmptyMessage(1);
// 下载完成
if (numread < 0){
mUpdateProgressHandler.sendEmptyMessage(2);
break;
}
fos.write(buffer, 0, numread);
}
fos.close();
is.close();
}
}catch(Exception e){
e.printStackTrace();
}
}
}).start();
}
/**
* 接收消息
*/
private Handler mUpdateProgressHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:
// 设置进度条
mProgressBar.setProgress(mProgress);
break;
case 2:
// 隐藏当前下载对话框
mDownloadDialog.dismiss();
// 安装 APK 文件
installAPK();
}
};
};
/*
* 下载到本地后执行安装
*/
protected void installAPK() {
File apkFile = new File(mSavePath, mVersion_name);
if (!apkFile.exists()){
return;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
// 安装完成后,启动app(源码中少了这句话)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Uri uri = Uri.parse("file://" + apkFile.toString());
intent.setDataAndType(uri, "application/vnd.android.package-archive");
mContext.startActivity(intent);
}
最后是mainfest权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!--往sdcard中写入数据的权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--在sdcard中创建/删除文件的权限 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
API版本不能设置太高:
apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.example.alex233.update"
minSdkVersion 16
targetSdkVersion 22
versionCode 11
versionName "2.9"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.+'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
//以下SDK开发者请根据需要自行选择
//bmob-sdk:Bmob的android sdk包,包含了Bmob的数据存储、文件等服务,以下是最新的bmob-sdk:
//3.5.5:请务必查看下面注释[1]
compile 'cn.bmob.android:bmob-sdk:3.6.3'
//bmob-push:Bmob的推送包
compile 'cn.bmob.android:bmob-push:0.8'
//bmob-im:Bmob的即时通讯包,注意每个版本的im依赖特定版本的bmob-sdk,具体的依赖关系可查看下面注释[2]
compile 'cn.bmob.android:bmob-im:aaa@qq.com'
//如果你想应用能够兼容Android6.0,请添加此依赖(org.apache.http.legacy.jar)
compile 'cn.bmob.android:http-legacy:1.0'
}
以上就是版本更新的内容了;
其实可以用android自带的download下载器
在dialog点击确认的点击事件中:
Intent intent = new Intent();
intent.setData(Uri.parse(url));//Url 就是你要打开的网址
intent.setAction(Intent.ACTION_VIEW);
startActivity(intent); //启动浏览器
就很简单,不需要下面的一大堆了
完整代码:
https://github.com/IMAlex233/update.git
上一篇: SwiftUI - Button
下一篇: 第三方服务之Bmob——答题系统小项目