「java自动更新apk」java自动更新配置文件
本篇文章给大家谈谈java自动更新apk,以及java自动更新配置文件对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。
本文目录一览:
如何简单实现安卓app自动更新功能
第一步 服务器端:
服务端提供一个借口,或者网址,我这里就用的服务器是tomcat,这里提供一个网址如下:
//也就是一个json数据接口
public static final String UPDATE_URL = "";
我们来看下json数据参数:
{
//app名字
appname: "爱新闻1.1",
//服务器版本号
serverVersion: "2",
//服务器标志
serverFlag: "1",
//是否强制更新
lastForce: "1",
//apk下载地址,这里我已经下载了官方的apk,放到了服务器里面
updateurl: "",
//版本的更新的描述
upgradeinfo: "V1.1版本更新,你想不想要试一下哈!!!"
}
第二步 客户端需要实现:
首先我们要去解析服务端给的json,那么我们就要来创建一个model类了(代码过多,这里只有字段,getter和setter方法自己创建):
//app名字
private String appname;
//服务器版本
private String serverVersion;
//服务器标志
private String serverFlag;
//强制升级
private String lastForce;
//app最新版本地址
private String updateurl;
//升级信息
private String upgradeinfo;
在这里使用了一个辅助类,基本和model字段差不多:
public class UpdateInformation {
public static String appname = MyApplication.getInstance()
.getResources().getString(R.string.app_name);
public static int localVersion = 1;// 本地版本
public static String versionName = ""; // 本地版本名
public static int serverVersion = 1;// 服务器版本
public static int serverFlag = 0;// 服务器标志
public static int lastForce = 0;// 之前强制升级版本
public static String updateurl = "";// 升级包获取地址
public static String upgradeinfo = "";// 升级信息
public static String downloadDir = "wuyinlei";// 下载目录
}
在进入app的时候,这个时候如果检测到服务器端有了新的版本,就回弹出提示框,提示我们更新。这个我们在MainActivity里面处理逻辑(onCreate()方法里面):
OkhttpManager.getAsync(Config.UPDATE_URL, new OkhttpManager.DataCallBack() {
@Override
public void requestFailure(Request request, Exception e) {
}
@Override
public void requestSuccess(String result) {
try {
Log.d("wuyiunlei",result);
JSONObject object = new JSONObject(result);
UpdateInfoModel model = new UpdateInfoModel();
model.setAppname(object.getString("appname"));
model.setLastForce(object.getString("lastForce"));
model.setServerFlag(object.getString("serverFlag"));
model.setServerVersion(object.getString("serverVersion"));
model.setUpdateurl(object.getString("updateurl"));
model.setUpgradeinfo(object.getString("upgradeinfo"));
tmpMap.put(DeliverConsts.KEY_APP_UPDATE, model);
} catch (JSONException e) {
e.printStackTrace();
}
//发送广播
sendBroadcast(new Intent(UpdateReceiver.UPDATE_ACTION));
}
});
当然了,我们也要注册和结束广播:
/**
* 广播注册
*/
private void registerBroadcast() {
mUpdateReceiver = new UpdateReceiver(false);
mIntentFilter = new IntentFilter(UpdateReceiver.UPDATE_ACTION);
this.registerReceiver(mUpdateReceiver, mIntentFilter);
}
/**
* 广播卸载
*/
private void unRegisterBroadcast() {
try {
this.unregisterReceiver(mUpdateReceiver);
} catch (Exception e) {
e.printStackTrace();
}
}
接下来我们看下我们自定义的广播接收者UpdateReceiver .java:
public class UpdateReceiver extends BroadcastReceiver {
private AlertDialog.Builder mDialog;
public static final String UPDATE_ACTION = "wuyinlei_aixinwen";
private SharedPreferencesHelper mSharedPreferencesHelper;
private boolean isShowDialog;
public UpdateReceiver() {
}
public UpdateReceiver(boolean isShowDialog) {
super();
this.isShowDialog = isShowDialog;
}
@Override
public void onReceive(Context context, Intent intent) {
mSharedPreferencesHelper = mSharedPreferencesHelper
.getInstance(MyApplication.getInstance());
//当然了,这里也可以直接new处hashmap
HashMap tempMap = MyApplication.getInstance()
.getTempMap();
UpdateInfoModel model = (UpdateInfoModel) tempMap
//就是一个标志
.get(DeliverConsts.KEY_APP_UPDATE);
try {
/**
* 获取到当前的本地版本
*/
UpdateInformation.localVersion = MyApplication
.getInstance()
//包管理独享
.getPackageManager()
//包信息
.getPackageInfo(
MyApplication.getInstance()
.getPackageName(), 0).versionCode;
/**
* 获取到当前的版本名字
*/
UpdateInformation.versionName = MyApplication
.getInstance()
.getPackageManager()
.getPackageInfo(
MyApplication.getInstance()
.getPackageName(), 0).versionName;
} catch (Exception e) {
e.printStackTrace();
}
//app名字
UpdateInformation.appname = MyApplication.getInstance()
.getResources().getString(R.string.app_name);
//服务器版本
UpdateInformation.serverVersion = Integer.parseInt(model
.getServerVersion());
//服务器标志
UpdateInformation.serverFlag = Integer.parseInt(model.getServerFlag());
//强制升级
UpdateInformation.lastForce = Integer.parseInt(model.getLastForce());
//升级地址
UpdateInformation.updateurl = model.getUpdateurl();
//升级信息
UpdateInformation.upgradeinfo = model.getUpgradeinfo();
//检查版本
checkVersion(context);
}
/**
* 检查版本更新
*
* @param context
*/
public void checkVersion(Context context) {
if (UpdateInformation.localVersion UpdateInformation.serverVersion) {
// 需要进行更新
mSharedPreferencesHelper.putIntValue(
//有新版本
SharedPreferencesTag.IS_HAVE_NEW_VERSION, 1);
//更新
update(context);
} else {
mSharedPreferencesHelper.putIntValue(
SharedPreferencesTag.IS_HAVE_NEW_VERSION, 0);
if (isShowDialog) {
//没有最新版本,不用升级
noNewVersion(context);
}
clearUpateFile(context);
}
}
/**
* 进行升级
*
* @param context
*/
private void update(Context context) {
if (UpdateInformation.serverFlag == 1) {
// 官方推荐升级
if (UpdateInformation.localVersion UpdateInformation.lastForce) {
//强制升级
forceUpdate(context);
} else {
//正常升级
normalUpdate(context);
}
} else if (UpdateInformation.serverFlag == 2) {
// 官方强制升级
forceUpdate(context);
}
}
/**
* 没有新版本
* @param context
*/
private void noNewVersion(final Context context) {
mDialog = new AlertDialog.Builder(context);
mDialog.setTitle("版本更新");
mDialog.setMessage("当前为最新版本");
mDialog.setNegativeButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
/**
* 强制升级 ,如果不点击确定升级,直接退出应用
*
* @param context
*/
private void forceUpdate(final Context context) {
mDialog = new AlertDialog.Builder(context);
mDialog.setTitle("版本更新");
mDialog.setMessage(UpdateInformation.upgradeinfo);
mDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent mIntent = new Intent(context, UpdateService.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mIntent.putExtra("appname", UpdateInformation.appname);
mIntent.putExtra("appurl", UpdateInformation.updateurl);
//启动服务
context.startService(mIntent);
}
}).setNegativeButton("退出", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 直接退出应用
//ManagerActivity.getInstance().finishActivity();
System.exit(0);
}
}).setCancelable(false).create().show();
}
/**
* 正常升级,用户可以选择是否取消升级
*
* @param context
*/
private void normalUpdate(final Context context) {
mDialog = new AlertDialog.Builder(context);
mDialog.setTitle("版本更新");
mDialog.setMessage(UpdateInformation.upgradeinfo);
mDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent mIntent = new Intent(context, UpdateService.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//传递数据
mIntent.putExtra("appname", UpdateInformation.appname);
mIntent.putExtra("appurl", UpdateInformation.updateurl);
context.startService(mIntent);
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
/**
* 清理升级文件
*
* @param context
*/
private void clearUpateFile(final Context context) {
File updateDir;
File updateFile;
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
updateDir = new File(Environment.getExternalStorageDirectory(),
UpdateInformation.downloadDir);
} else {
updateDir = context.getFilesDir();
}
updateFile = new File(updateDir.getPath(), context.getResources()
.getString(R.string.app_name) + ".apk");
if (updateFile.exists()) {
Log.d("update", "升级包存在,删除升级包");
updateFile.delete();
} else {
Log.d("update", "升级包不存在,不用删除升级包");
}
}
}
在app开发中怎么实现app打开自动更新
Android开发如何实现APP自动更新
先来看看要实现的效果图:
对于安卓用户来说,手机应用市场说满天飞可是一点都不夸张,比如小米,魅族,百度,360,机锋,应用宝等等,当我们想上线一款新版本APP时,先不说渠道打包的麻烦,单纯指上传APP到各大应用市场的工作量就已经很大了,好不容易我们把APP都上传完了,突然发现一个会导致应用闪退的小Bug,这时那个崩溃啊,明明不是很大的改动,难道我们还要再去重新去把各大应用市场的版本再上传更新一次?相信我,运营人员肯定会弄死你的!!
有问题,自然就会有解决问题的方案,因此我们就会想到如果在APP里内嵌自动更新的功能,那么我们将可以省去很多麻烦,当然关于这方面功能的第三方SDK有很多。
好了,言归正传,今天我们自己来实现下关于APP自动更新。
流程其实并不复杂:当用户打开APP的时候,我们让APP去发送一个检查版本的网络请求,或者利用服务端向APP推送一个透传消息来检查APP的版本,如果当前APP版本比服务器上的旧,那么我们就提醒用户进行下载更新APP,当然在特定的情况下,我们也可以强制的让用户去升级,当然这是很不友好的,尽可能的减少这样的做法。
好了,来梳理下流程,首先既然是一个APP的更新,那么我们就需要去下载新的APP,然后我们需要一个通知来告诉用户当前的下载进度,再来当APP安装包下载完成后,我们需要去系统的安装程序来对APP进行安装更新。
知识点:
下载:异步HTTP请求文件下载,并监听当前下载进度(这里我采用了okhttp)
通知:Notification(具体用法请自行翻阅API文档)
安装:Intent (具体用法请自行翻阅API文档)
来看下具体实现代码:
我们需要一个后台服务来支撑App的下载
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.NotificationCompat;
import com.fangku.commonlibrary.utils.StorageUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import java.io.File;
import okhttp3.Call;
/**
* 自动下载更新apk服务
* Create by: chenwei.li
* Date: 2016-08-14
* time: 09:50
* Email: lichenwei.me@foxmail.com
*/
public class DownloadService extends Service {
private String mDownloadUrl;//APK的下载路径
private NotificationManager mNotificationManager;
private Notification mNotification;
@Override
public void onCreate() {
super.onCreate();
mNotificationManager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent == null) {
notifyMsg("温馨提醒", "文件下载失败", 0);
stopSelf();
}
mDownloadUrl = intent.getStringExtra("apkUrl");//获取下载APK的链接
downloadFile(mDownloadUrl);//下载APK
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void notifyMsg(String title, String content, int progress) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);//为了向下兼容,这里采用了v7包下的NotificationCompat来构造
builder.setSmallIcon(R.mipmap.icon_login_logo).setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_login_logo)).setContentTitle(title);
if (progress 0 progress 100) {
//下载进行中
builder.setProgress(100, progress, false);
} else {
builder.setProgress(0, 0, false);
}
builder.setAutoCancel(true);
builder.setWhen(System.currentTimeMillis());
builder.setContentText(content);
if (progress = 100) {
//下载完成
builder.setContentIntent(getInstallIntent());
}
mNotification = builder.build();
mNotificationManager.notify(0, mNotification);
}
/**
* 安装apk文件
*
* @return
*/
private PendingIntent getInstallIntent() {
File file = new File(StorageUtil.DOWNLOAD_DIR + "APP文件名");
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(Uri.parse("file://" + file.getAbsolutePath()), "application/vnd.android.package-archive");
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
/**
* 下载apk文件
*
* @param url
*/
private void downloadFile(String url) {
OkHttpUtils.get().url(url).build().execute(new FileCallBack(StorageUtil.DOWNLOAD_DIR, "APP文件名") {
@Override
public void onError(Call call, Exception e, int id) {
notifyMsg("温馨提醒", "文件下载失败", 0);
stopSelf();
}
@Override
public void onResponse(File response, int id) {
//当文件下载完成后回调
notifyMsg("温馨提醒", "文件下载已完成", 100);
stopSelf();
}
@Override
public void inProgress(float progress, long total, int id) {
//progress*100为当前文件下载进度,total为文件大小
if ((int) (progress * 100) % 10 == 0) {
//避免频繁刷新View,这里设置每下载10%提醒更新一次进度
notifyMsg("温馨提醒", "文件正在下载..", (int) (progress * 100));
}
}
});
}
}
然后我们只需要在我们想要的更新APP的时候去调起这个服务即可,比如在系统设置里的"版本检查"等
Intent intent = new Intent(mContext, DownloadService.class);
intent.putExtra("apkUrl", "APK下载地址");
startService(intent);
总结
这里我只是粗略演示本地自动更新APP的功能,在实际应用中,我们应该配合服务端来做,比如在用户启动APP的时候去比对版本号,如果版本号低于服务器的版本号,那么此时服务端应该给客户端一个透传推送,这里的推送内容应该为新版本APP的下载地址,此时就可以根据该地址来下载新版APP了,当遇到重大更新,不再对老版本进行兼容的时候,可以强制用户升级,这里的方案有很多,比如调用系统级对话框,让用户没办法取消等操作,这里就不做更多描述。以上就是这篇文章的全部内容,希望对有需要的人能有所帮助。
java安装的软件总是提醒更新该怎样设置避免
打开控制面板,找到Java控制,双击打开,里边有个更新 的标签页,切换过去之后可以看到,可以选择是否更新和更新频率等,去掉更新就可以了。。
下次提示更新的时候也可以直接打开右下角的托盘里的那个升级图标,直接进到升级设置界面的。
java自动更新apk的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于java自动更新配置文件、java自动更新apk的信息别忘了在本站进行查找喔。
发布于:2022-11-22,除非注明,否则均为
原创文章,转载请注明出处。