UpdateAPK工具类
/**
* 更新APK
*/
public class UpdateAPK {
/* 下载中 */
private static final int DOWNLOAD = 1;
/* 下载结束 */
private static final int DOWNLOAD_FINISH = 2;
/* 下载保存路径 */
private String mSavePath;
/* 记录进度条数量 */
private int progress;
/* 是否取消更新 */
private boolean cancelUpdate = false;
private String str_appname;
private String str_downurl;
private Context mContext;
public int version;
/* 更新进度条 */
private ProgressBar mProgress;
private Dialog mDownloadDialog;
public UpdateAPK(Context context) {
this.mContext = context;
}
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
// 正在下载
case DOWNLOAD:
// 设置进度条位置
mProgress.setProgress(progress);
break;
case DOWNLOAD_FINISH:
// 安装文件
installApk();
break;
default:
break;
}
}
};
/**
* 检查软件是否有更新版本
*
* @return
*/
public void isUpdate() {
//获取当前软件版本号
String versionName = getVersionName(mContext);
//通过服务器获得版本号
if (!Utils.isNetworkAvailable(mContext)) {
Toast.makeText(mContext, "请检查网络", Toast.LENGTH_LONG).show();
} else {
//网络请求 判断是否更新
showNoticeDialog(1)
}
}
/**
* 获取当前版本号
*
* @param context
* @return
*/
private String getVersionName(Context context) {
String versionName = "";
try {
PackageInfo packageInfo = context.getApplicationContext().getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return versionName;
}
/**
* 显示软件更新对话框
*/
private void showNoticeDialog(int force) {
// 构造软件下载对话框
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle(R.string.soft_updating);
// 给下载对话框增加进度条
final LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.soft_update, null);
mProgress = v.findViewById(R.id.update_progress);
builder.setView(v);
builder.setCancelable(false);
if (force == 2) {
// 取消更新
builder.setNegativeButton(R.string.soft_update_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
cancelUpdate = true;
}
});
}
mDownloadDialog = builder.create();
mDownloadDialog.show();
// 下载文件
downloadApk();
}
/**
* 下载apk文件
*/
private void downloadApk() {
// 启动新线程下载软件
new downloadApkThread().start();
}
/**
* 下载文件线程
*/
private class downloadApkThread extends Thread {
@Override
public void run() {
try {
// 判断SD卡是否存在,并且是否具有读写权限
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// 获得存储卡的路径
String sdpath = Environment.getExternalStorageDirectory() + "/";
mSavePath = sdpath + "download";
URL url = new URL(str_downurl);
// 创建连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
// 获取文件大小
int length = conn.getContentLength();
// 创建输入流
InputStream is = conn.getInputStream();
File file = new File(mSavePath);
// 判断文件目录是否存在
if (!file.exists()) {
file.mkdir();
}
File apkFile = new File(mSavePath, str_appname);
FileOutputStream fos = new FileOutputStream(apkFile);
int count = 0;
// 缓存
byte buf[] = new byte[1024];
// 写入到文件中
do {
int numread = is.read(buf);
count += numread;
// 计算进度条位置
progress = (int) (((float) count / length) * 100);
// 更新进度
mHandler.sendEmptyMessage(DOWNLOAD);
if (numread <= 0) {
// 下载完成
mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
break;
}
// 写入文件
fos.write(buf, 0, numread);
} while (!cancelUpdate);// 点击取消就停止下载.
fos.close();
is.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 取消下载对话框显示
mDownloadDialog.dismiss();
}
}
/**
* 安装APK文件
*/
public void installApk() {
File apkfile = new File(mSavePath, str_appname);
if (!apkfile.exists()) {
return;
}
Intent intent = new Intent(Intent.ACTION_VIEW);
if (null != apkfile) {
try {
//兼容7.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileProvider", apkfile);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
//兼容8.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
boolean hasInstallPermission = mContext.getPackageManager().canRequestPackageInstalls();
if (!hasInstallPermission) {
startInstallPermissionSettingActivity();
return;
}
}
} else {
intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
if (mContext.getPackageManager().queryIntentActivities(intent, 0).size() > 0) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
Log.i("name", mContext.getPackageName());
Uri contentUri = FileProvider.getUriForFile(mContext, mContext.getPackageName() + ".fileProvider", apkfile);
intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
private void startInstallPermissionSettingActivity() {
//注意这个是8.0新API
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
}
AndroidManifest.xml配置
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="app包名.fileProvider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
file_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="image"
path="." />
</paths>