APP版本升級(適配不同版本)

現(xiàn)在在一家外包公司,所以經(jīng)常地接到一些不同的項目,基本上每個項目都需要用到版本升級,故在此總結(jié)一下版本升級的方法以及不同安卓版本的適配方法。

版本更新工具類:

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) {
        //三個參數(shù)分別對應(yīng):APK的下載路徑,更新彈窗的標題,更新彈窗的內(nèi)容(一般放版本的更新內(nèi)容)
        // 在下載之前應(yīng)該刪除已有文件
        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));
        //設(shè)置title
        request.setTitle(title);
        // 設(shè)置描述
        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);
    }

    /**
     * 對應(yīng) {@link Activity }
     */
    public void resume() {
        //設(shè)置監(jiān)聽Uri.parse("content://downloads/my_downloads")
        weakReference.get().getContentResolver().registerContentObserver(Uri.parse("content://downloads/my_downloads"), true,
                mDownLoadChangeObserver);
        // 注冊廣播,監(jiān)聽APK是否下載完成
        weakReference.get().registerReceiver(mDownloadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    }

    /**
     * 對應(yīng){@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()) {
                //已經(jīng)下載的字節(jié)數(shù)
                bytesAndStatus[0] = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                //總需下載的字節(jié)數(shù)
                bytesAndStatus[1] = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                //狀態(tài)所在的列索引
                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();
        }
    }

    //監(jiān)聽下載狀態(tài)
    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) {

                //先獲取是否有安裝未知來源應(yīng)用的權(quán)限
                haveInstallPermission = context.getPackageManager().canRequestPackageInstalls();
                if (!haveInstallPermission) {//沒有權(quán)限
                    // 彈窗,并去設(shè)置頁面授權(quán)
                    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);
            }

            // 安裝應(yīng)用
            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是否擁有安裝未知來源應(yīng)用的權(quán)限,檢查權(quán)限的工具類(提示:該工具類因為是繼承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所以需要獲得安裝未知來源的權(quán)限
        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) {
            // 授權(quán)成功
            if (sListener != null) {
                sListener.permissionSuccess();
            }
        } else {
            // 授權(quán)失敗
            if (sListener != null) {
                sListener.permissionFail();
            }
        }
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        sListener = null;
    }
}

在獲取安裝權(quán)限之后,需要打開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文件夾下創(chuàng)建 xml文件,并創(chuàng)建update_files.xml:

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <!--文件權(quán)限配置-->
    <!--1、對應(yīng)內(nèi)部內(nèi)存卡根目錄:Context.getFileDir()-->
    <files-path
        name="root"
        path="/" />
    <!--2、對應(yīng)應(yīng)用默認緩存根目錄:Context.getCacheDir()-->
    <cache-path
        name="cache"
        path="/" />
    <!--3、對應(yīng)外部內(nèi)存卡根目錄:Environment.getExternalStorageDirectory()-->
    <external-path
        name="path"
        path="/" />
    <external-path
        name="ext_root"
        path="pictures/" />
    <!--4、對應(yīng)外部內(nèi)存卡根目錄下的APP公共目錄:Context.getExternalFileDir(String)-->
    <external-files-path
        name="ext_pub"
        path="/" />
    <!--5、對應(yīng)外部內(nèi)存卡根目錄下的APP緩存目錄:Context.getExternalCacheDir()-->
    <external-cache-path
        name="ext_cache"
        path="/" />
</paths>

以上,就完成了版本自動升級工具的封裝。在Activity中,只要創(chuàng)建AppDownloadManager實例對象,并調(diào)用該對象的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>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容