(PS:也可以用第三方公司出的,比如腾讯的Bugly等,也挺方便的,不过apk要上传到Bugly的平台上,然后公司要求在自己平台上,所以没有使用。)
-------------------------------------我是分割分割君---------------------------------
大家都知道应用升级,也都体验过应用升级,而开发步骤也一般分为这么几步(如果图片里面缺少啥步骤,欢迎指出。):
我们就按照一步步来分析:
从服务器上获取版本信息,怎么做呢,只要和你们后台开发人员搞好关系即可。哈哈。一般需要他们提供这几个字段。
{
"versionCode": "1",
"versionName": "1.0",
"apkUrl": "http://java.linuxlearn.net/shelwee/Finances.apk",
"updateTitle": "更新提示" ,
"changeLog":"1.修复xxx Bug;\n2.更新UI界面."
}
获取本地APP的versionCode
public static int getPackageVersionCode(Context context){
PackageManager manager = context.getPackageManager();
PackageInfo packageInfo = null;
try {
packageInfo = manager.getPackageInfo(context.getPackageName(),0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if(packageInfo != null){
return packageInfo.versionCode;
}else{
return 1;
}
}
然后和服务器那边传过来的versionCode字段进行比较,如果比我们本地获取的APP的versionCode 大。那就进行下一步
3.我们也看到了,这里我分成了Android6.0为分割线做区别。因为Android6.0开始后,单纯的在AndroidManifest.xml中定义权限已经不够了。需要再代码中动态让用户来确定才能给APP相应的权限。所以我们APP在AndroidManifest.xml中还是定义
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
因为在Android6.0系统下,就等于获取到了这二者的权限。(下载APK当然要网络权限和把文件写入存储的权限)
那如果在Android6.0及以上的时候。我们该怎么来做,因为我是使用RxJava的。所以这里也推荐一个RxPermissions来进行获取权限。
RxPermissions项目地址 还有简书上达达达达sky 写的基于Rxjava 1.x的基础上的RxPermissions源码解析 (其中最新的RxPermissions中,RxPermissions.getInstance(this)方法,改为了new RxPermissions(this))
那我们简单来看下是怎么使用:
new RxPermissions(UpdateActivity.this)
.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.INTERNET)
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
//当用户按了确定按钮,aBoolean为true,否则为false
if (aBoolean) {
//成功授予权限,则跳出提示框,是否下载APK
createAlert();
} else {
//用户拒绝同意授予权限
Toast.makeText(UpdateActivity.this, "权限不足,无法下载更新。", Toast.LENGTH_LONG).show();
}
}
});
这里就提一点:request方法是当申请多个权限的时候,只要有一个权限用户不同意授予,aBoolean就会为false,如果想要为每个权限的授予专门做处理,可以把request改为requestEach。更多的使用还是请看上面的相关文章链接。
注意:由于在请求权限的过程中app有可能会被重启,所以权限请求必须放在初始化的阶段,比如在Activity.onCreate/onResume, 或者View.onFinishInflate方法中。如果不这样处理,那么如果app在请求过程中重启的话,权限请求结果将不会发送给订阅者即subscriber。
4.好了。现在我们也已经把下载APK的所需的权限也搞定了,当用户同意授予相应的权限的时候,接下去就是跳出对话框,询问用户是否需要更新APK,这里就是单纯的创建一个对话框询问即可,估计大家都会,直接上代码:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示标题");
builder.setMessage("提示内容");
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
Toast.makeText(UpdateActivity.this, "取消更新。", Toast.LENGTH_LONG).show();
}
});
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//进入下一步,去确定是WiFi还是流量
confirmWifi();
}
});
//让对话框不能通过点击返回按钮或者其他区域让对话框消失
builder.setCancelable(false);
builder.create().show();
5.用户如果点击确定按钮。然后我们这时候就要判断,是不是WiFi情况下,如果是WiFi情况下就直接进行更新,如果不是,再创建对话框,然后询问用户,是否确定需要通过流量来进行下载:
public void confirmWifi(){
if(isWiFi(UpdateActivity.this)){
startService(new Intent(UpdateActivity.this, UpdateService.class));
Toast.makeText(UpdateActivity.this, "开始下载。", Toast.LENGTH_LONG).show();
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示");
builder.setMessage("是否要用流量进行下载更新");
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
Toast.makeText(UpdateActivity.this, "取消更新。", Toast.LENGTH_LONG).show();
}
});
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
startService(new Intent(UpdateActivity.this, UpdateService.class));
Toast.makeText(UpdateActivity.this, "开始下载。", Toast.LENGTH_LONG).show();
}
});
builder.setCancelable(false);
builder.create().show();
}
}
//判断是不是WiFi状态
public static boolean isWiFi(Context cxt) {
ConnectivityManager cm = (ConnectivityManager) cxt
.getSystemService(Context.CONNECTIVITY_SERVICE);
// wifi的状态:ConnectivityManager.TYPE_WIFI
// 3G的状态:ConnectivityManager.TYPE_MOBILE
NetworkInfo.State state = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.getState();
return NetworkInfo.State.CONNECTED == state;
}
记得查询当前是不是WiFi状态也要加权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
然后我们就startService(new Intent(UpdateActivity.this, UpdateService.class));
来进行接下去的下载之路,因为一般下载都是在后台,所以都是放在Service中进行操作的。
这里我顺便放篇链接,关于Service的,觉得写得不错,大家可以看下: 深入理解Android的startservice和bindservice
6.我们前面的条件都ok了。用户也都按了确定之后,就开始我们正式的下载之路,启动Service来进行相关的后续操作: 第六个部分我会分几块来讲解
基本的使用及介绍大家看下面文章介绍: Android系统下载管理DownloadManager
所以我们通过DownLoadManager来进行APK的下载,代码如下:
public void downApk() {
//当发现本地以及有该APK的时候先进行删除再下载,不然下载下来多次之后手机自动会变成Chint-1.apk,Chint-2.apk等
File apkFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath()+"/Chint.apk");
if(apkFile.exists()){
Toast.makeText(this,"已经有apk存在,将要删除",Toast.LENGTH_LONG).show();
apkFile.delete();
}
DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DOWNURL));
request.setMimeType("application/vnd.android.package-archive");
//request.setDescription("XXXX");
//request.setTitle("XXX");
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, "Chint.apk");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
manager.enqueue(request);
}
DownloadManager.ACTION_DOWNLOAD_COMPLETE
的广播,所以我们只要刚开始在启动Service的时候,注册一个广播,监听
DownloadManager.ACTION_DOWNLOAD_COMPLETE
,然后当下载完成后,在BroadcastReceiver中调用安装APK的方法即可。是不是很方便。public void receiverRegist() {
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
installApk(context);
stopSelf();
}
};
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(receiver, filter);
}
然后进行安装APK,安装结束后调用stopSelf();来摧毁这个Service当Service被摧毁的时候,要记得注销这个广播哦:
@Override
public void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
public void installApk(Context context) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(
Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "Chint.apk")),
"application/vnd.android.package-archive");
context.startActivity(intent);
}
这里额外再传送个链接,如果想卸载软件咋办,请看下面文章链接: Android程序中实现APK的安装与卸载
因为7.0之后权限变得更加严格,通过Intent来安装APK需要添加一个Provider,这里我Demo没写,给出下面文章链接,大家可以看下(下面第一篇里面也说明了为什么7.0下用普通的Intent安装会报错):
最后上一下代码全文 UpdateActivity.java:
package yunyuan.androiddemo.appupdate;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.Toast;
import com.tbruyelle.rxpermissions.RxPermissions;
import rx.functions.Action1;
import yunyuan.androiddemo.R;
/**
* Created by willy on 17/1/10.
*/
public class UpdateActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_update);
new RxPermissions(UpdateActivity.this)
.request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.INTERNET)
.subscribe(new Action1<Boolean>() {
@Override
public void call(Boolean aBoolean) {
if (aBoolean) {
createAlert();
} else {
Toast.makeText(UpdateActivity.this, "权限不足,无法下载更新。", Toast.LENGTH_LONG).show();
}
}
});
}
public void createAlert() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示标题");
builder.setMessage("提示内容");
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
Toast.makeText(UpdateActivity.this, "取消更新。", Toast.LENGTH_LONG).show();
}
});
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
confirmWifi();
}
});
builder.setCancelable(false);
builder.create().show();
}
public void confirmWifi() {
if (isWiFi(UpdateActivity.this)) {
startService(new Intent(UpdateActivity.this, UpdateService.class));
Toast.makeText(UpdateActivity.this, "开始下载。", Toast.LENGTH_LONG).show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("提示");
builder.setMessage("是否要用流量进行下载更新");
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
Toast.makeText(UpdateActivity.this, "取消更新。", Toast.LENGTH_LONG).show();
}
});
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
startService(new Intent(UpdateActivity.this, UpdateService.class));
Toast.makeText(UpdateActivity.this, "开始下载。", Toast.LENGTH_LONG).show();
}
});
builder.setCancelable(false);
builder.create().show();
}
}
public static boolean isWiFi(Context cxt) {
ConnectivityManager cm = (ConnectivityManager) cxt
.getSystemService(Context.CONNECTIVITY_SERVICE);
// wifi的状态:ConnectivityManager.TYPE_WIFI
// 3G的状态:ConnectivityManager.TYPE_MOBILE
NetworkInfo.State state = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.getState();
return NetworkInfo.State.CONNECTED == state;
}
}
UpadateService.java
package yunyuan.androiddemo.appupdate;
import android.app.DownloadManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
import java.io.File;
/**
* Created by willy on 17/1/9.
*/
public class UpdateService extends Service {
public static final String DOWNURL = "http://dakaapp.troila.com/download/daka.apk?v=3.0";
BroadcastReceiver receiver;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
receiverRegist();
downApk();
return Service.START_STICKY;
}
public void receiverRegist() {
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
installApk(context);
stopSelf();
}
};
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(receiver, filter);
}
public void installApk(Context context) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(
Uri.fromFile(new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "Chint.apk")),
"application/vnd.android.package-archive");
context.startActivity(intent);
}
public void downApk() {
File apkFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath()+"/Chint.apk");
if(apkFile.exists()){
Toast.makeText(this,"已经有apk存在,将要删除",Toast.LENGTH_LONG).show();
apkFile.delete();
}
DownloadManager manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DOWNURL));
request.setMimeType("application/vnd.android.package-archive");
//request.setDescription("XXXX");
//request.setTitle("XXX");
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, "Chint.apk");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
manager.enqueue(request);
}
@Override
public void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
}