现在在一家外包公司,所以经常地接到一些不同的项目,基本上每个项目都需要用到版本升级,故在此总结一下版本升级的方法以及不同安卓版本的适配方法。
版本更新工具类:
public class AppDownloadManager {
public static final String TAG = "AppDownloadManager";
private String apkName = "newapk.apk";
private WeakReference<Activity> weakReference;
private DownloadManager mDownloadManager;
private DownloadChangeObserver mDownLoadChangeObserver;
private DownloadReceiver mDownloadReceiver;
private long mReqId;
private OnUpdateListener mUpdateListener;
private Context mContext;
private PopupWindow mPopupWindow;
private ProgressBar mProgress;
private Dialog downloadDialog;
public AppDownloadManager(Activity activity) {
mContext = activity;
weakReference = new WeakReference<Activity>(activity);
mDownloadManager = (DownloadManager) weakReference.get().getSystemService(Context.DOWNLOAD_SERVICE);
mDownLoadChangeObserver = new DownloadChangeObserver(new Handler());
mDownloadReceiver = new DownloadReceiver();
}
//版本更新弹窗
public void showNoticeDialog(final String apkUrl, final String title, final String des) {
View view = View.inflate(mContext, R.layout.sys_pop_version_update, null);
TextView tvVersionDes = view.findViewById(R.id.tvVersionDes);//描述
TextView tvSure = view.findViewById(R.id.tvSure);//确定
TextView tvCancle = view.findViewById(R.id.tvCancle);//取消
tvVersionDes.setText(des);
tvSure.setOnClickListener(v -> {
mPopupWindow.dismiss();
downloadApk(apkUrl,title,des);
// showDownloadDialog(apkUrl,title,des);
});
tvCancle.setOnClickListener(v -> mPopupWindow.dismiss());
mPopupWindow = PopWindowUtil.getInstance()
.makePopupWindow(mContext, view, ViewGroup.LayoutParams.MATCH_PARENT,true)
.showLocation(mContext, view, Gravity.CENTER, 0, 0,0);
}
public void setUpdateListener(OnUpdateListener mUpdateListener) {
this.mUpdateListener = mUpdateListener;
}
public void downloadApk(String apkUrl, String title, String desc) {
//三个参数分别对应:APK的下载路径,更新弹窗的标题,更新弹窗的内容(一般放版本的更新内容)
// 在下载之前应该删除已有文件
File apkFile = new File(weakReference.get().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), apkName);
if (apkFile != null && apkFile.exists()) {
apkFile.delete();
}
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUrl));
//设置title
request.setTitle(title);
// 设置描述
request.setDescription(desc);
// 完成后显示通知栏
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalFilesDir(weakReference.get(), Environment.DIRECTORY_DOWNLOADS, apkName);
request.setMimeType("application/vnd.android.package-archive");
//
mReqId = mDownloadManager.enqueue(request);
}
/**
* 取消下载
*/
public void cancel() {
mDownloadManager.remove(mReqId);
}
/**
* 对应 {@link Activity }
*/
public void resume() {
//设置监听Uri.parse("content://downloads/my_downloads")
weakReference.get().getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"), true,
mDownLoadChangeObserver);
// 注册广播,监听APK是否下载完成
weakReference.get().registerReceiver(mDownloadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
/**
* 对应{@link Activity()} ()}
*/
public void onPause() {
weakReference.get().getContentResolver().unregisterContentObserver(mDownLoadChangeObserver);
weakReference.get().unregisterReceiver(mDownloadReceiver);
}
private void updateView() {
int[] bytesAndStatus = new int[]{0, 0, 0};
DownloadManager.Query query = new DownloadManager.Query().setFilterById(mReqId);
Cursor c = null;
try {
c = mDownloadManager.query(query);
if (c != null && c.moveToFirst()) {
//已经下载的字节数
bytesAndStatus[0] = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
//总需下载的字节数
bytesAndStatus[1] = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
//状态所在的列索引
bytesAndStatus[2] = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
}
} finally {
if (c != null) {
c.close();
}
}
if (mUpdateListener != null) {
mUpdateListener.update(bytesAndStatus[0], bytesAndStatus[1]);
}
Log.i(TAG, "下载进度:" + bytesAndStatus[0] + "/" + bytesAndStatus[1] + "");
}
class DownloadChangeObserver extends ContentObserver {
/**
* Creates a content observer.
*
* @param handler The handler to run {@link #onChange} on, or null if none.
*/
public DownloadChangeObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
updateView();
}
}
//监听下载状态
class DownloadReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
boolean haveInstallPermission;
// 兼容Android 8.0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//先获取是否有安装未知来源应用的权限
haveInstallPermission = context.getPackageManager().canRequestPackageInstalls();
if (!haveInstallPermission) {//没有权限
// 弹窗,并去设置页面授权
final AndroidOInstallPermissionListener listener = new AndroidOInstallPermissionListener() {
@Override
public void permissionSuccess() {
installApk(context, intent);
}
@Override
public void permissionFail() {
ToastUtil.show(R.string.sys_permission_fail);
}
};
AndroidOPermissionActivity.sListener = listener;
Intent intent1 = new Intent(context, AndroidOPermissionActivity.class);
context.startActivity(intent1);
} else {
installApk(context, intent);
}
} else {
installApk(context, intent);
}
}
}
/**
* @param context
* @param intent
*/
private void installApk(Context context, Intent intent) {
long completeDownLoadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
Log.e(TAG, "收到广播");
Uri uri;
Intent intentInstall = new Intent();
intentInstall.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intentInstall.setAction(Intent.ACTION_VIEW);
if (completeDownLoadId == mReqId) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { // 6.0以下
uri = mDownloadManager.getUriForDownloadedFile(completeDownLoadId);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { // 6.0 - 7.0
File apkFile = queryDownloadedApk(context, completeDownLoadId);
uri = Uri.fromFile(apkFile);
} else { // Android 7.0 以上
uri = FileProvider.getUriForFile(context,
context.getPackageName() + ".fileProvider",
new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), apkName));
Log.d("downloadtest",uri.toString());
intentInstall.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
// 安装应用
Log.e("zhouwei", "下载完成了");
intentInstall.setDataAndType(uri, "application/vnd.android.package-archive");
context.startActivity(intentInstall);
}
}
//通过downLoadId查询下载的apk,解决6.0以后安装的问题
public static File queryDownloadedApk(Context context, long downloadId) {
File targetApkFile = null;
DownloadManager downloader = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
if (downloadId != -1) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
Cursor cur = downloader.query(query);
if (cur != null) {
if (cur.moveToFirst()) {
String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
if (!TextUtils.isEmpty(uriString)) {
targetApkFile = new File(Uri.parse(uriString).getPath());
}
}
cur.close();
}
}
return targetApkFile;
}
public interface OnUpdateListener {
void update(int currentByte, int totalByte);
}
public interface AndroidOInstallPermissionListener {
void permissionSuccess();
void permissionFail();
}
}
在下载好APK后,安卓8.0的手机需要检查APP是否拥有安装未知来源应用的权限,检查权限的工具类(提示:该工具类因为是继承FragmentActivity,所以需要在AndroidManifest中声明该Activity):
public class AndroidOPermissionActivity extends FragmentActivity {
public static final int INSTALL_PACKAGES_REQUESTCODE = 1;
private AlertDialog mAlertDialog;
public static AppDownloadManager.AndroidOInstallPermissionListener sListener;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 弹窗提示,跟用户说明是为了升级我们的APP所以需要获得安装未知来源的权限
if (Build.VERSION.SDK_INT >= 26) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, INSTALL_PACKAGES_REQUESTCODE);
} else {
finish();
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case INSTALL_PACKAGES_REQUESTCODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (sListener != null) {
sListener.permissionSuccess();
finish();
}
} else {
//startInstallPermissionSettingActivity();
showDialog();
}
break;
}
}
private void showDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.app_name);
builder.setMessage(R.string.sys_apply_permission);
builder.setPositiveButton(R.string.sys_ensure, new DialogInterface.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onClick(DialogInterface dialogInterface, int i) {
startInstallPermissionSettingActivity();
mAlertDialog.dismiss();
}
});
builder.setNegativeButton(R.string.sys_cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
if (sListener != null) {
sListener.permissionFail();
}
mAlertDialog.dismiss();
finish();
}
});
mAlertDialog = builder.create();
mAlertDialog.show();
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void startInstallPermissionSettingActivity() {
//注意这个是8.0新API
Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, 1);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
// 授权成功
if (sListener != null) {
sListener.permissionSuccess();
}
} else {
// 授权失败
if (sListener != null) {
sListener.permissionFail();
}
}
finish();
}
@Override
protected void onDestroy() {
super.onDestroy();
sListener = null;
}
}
在获取安装权限之后,需要打开APK,即下载工具类的installApk()方法。在安卓7.0以后,需要配置provider来获取APK的位置并打开安装。
uri = FileProvider.getUriForFile(context,
context.getPackageName() + ".fileProvider",
new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), apkName));
配置FileProvider步骤如下:首先在AndroidManifest中声明Provider
<application
…
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileProvider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/update_files" />
</provider>
…
</application>
其次在res文件夹下创建 xml文件,并创建update_files.xml:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<!--文件权限配置-->
<!--1、对应内部内存卡根目录:Context.getFileDir()-->
<files-path
name="root"
path="/" />
<!--2、对应应用默认缓存根目录:Context.getCacheDir()-->
<cache-path
name="cache"
path="/" />
<!--3、对应外部内存卡根目录:Environment.getExternalStorageDirectory()-->
<external-path
name="path"
path="/" />
<external-path
name="ext_root"
path="pictures/" />
<!--4、对应外部内存卡根目录下的APP公共目录:Context.getExternalFileDir(String)-->
<external-files-path
name="ext_pub"
path="/" />
<!--5、对应外部内存卡根目录下的APP缓存目录:Context.getExternalCacheDir()-->
<external-cache-path
name="ext_cache"
path="/" />
</paths>
以上,就完成了版本自动升级工具的封装。在Activity中,只要创建AppDownloadManager实例对象,并调用该对象的showNoticeDialog方法,即可完成版本的自动升级。附上版本升级弹窗的xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:background="@drawable/btn_shape_gray_10"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
style="@style/textViewStyle"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:textColor="@color/text_color"
android:textStyle="bold"
android:textSize="18sp"
android:text="版本升级"/>
<TextView
android:id="@+id/tvVersionDes"
style="@style/textViewStyle"
android:layout_marginTop="20dp"
android:layout_marginBottom="30dp"
android:layout_gravity="center"
android:maxLines="8"
android:minLines="6"
android:scrollbars="vertical"
android:singleLine="false"
android:textColor="@color/black"
android:textSize="14sp" />
<LinearLayout
android:layout_marginTop="10dp"
android:layout_marginBottom="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal">
<TextView
android:id="@+id/tvSure"
android:textSize="14sp"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_marginTop="1dp"
android:layout_weight="1"
android:gravity="center"
android:textColor="@color/main_color"
android:text="@string/sys_update" />
<View
android:id="@+id/dialogCutOfRule"
android:layout_gravity="center"
android:layout_width="0.5dp"
android:layout_height="25dp"
android:background="@color/gray_bbb" />
<TextView
android:id="@+id/tvCancle"
android:textSize="14sp"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_marginTop="1dp"
android:layout_weight="1"
android:gravity="center"
android:text="@string/sys_cancel" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
网友评论