Android version download update

Posted by padiwak on Fri, 01 May 2020 23:24:42 +0200

Almost every function should have
Preparation: request version update to get the link to download apk,
For example:“ http://yibanyue.oss-cn-hangzhou.xxx.com/apk/yiyue.apk"
Process: request version update link to get the link, pop-up box to ask if it is updated, create apk folder locally, Download apk with DownloadManager, and put the path in the folder created earlier, monitor whether it is downloaded by broadcastreceiver, and activate the installation after downloading
critical code
To query and create folders in the pop-up box, Download (delete the irrelevant code by yourself):
Download folder name: apk folder name

DialogUtils.okAndCancel(mContext, pdesc, new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //Update APP
            if (!TextUtils.isEmpty(url)) {
                downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                if (isForce) {
                    Dialog dialog = DialogUtils.progress(getContext(), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            downloadManager.remove(SharedPreferencesUtils.getLong(getContext(), SPKey.APK_DOWN_ID, 0));
                            ActivityUtils.closeAll();
                        }
                    });
                }
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
                File fileDir = Environment.getExternalStoragePublicDirectory(DOWNLOAD_FOLDER_NAME);
                if (fileDir.exists() && fileDir.isDirectory()) {
                    request.setDestinationInExternalPublicDir(DOWNLOAD_FOLDER_NAME, url.substring(url.lastIndexOf("/") + 1));
                } else {
                    fileDir.mkdirs();
                    request.setDestinationInExternalPublicDir(DOWNLOAD_FOLDER_NAME, url.substring(url.lastIndexOf("/") + 1));
                }
                long downloadId = downloadManager.enqueue(request);
                downId = downloadId;
                SharedPreferencesUtils.saveLong(getContext(), SPKey.APK_DOWN_ID, downloadId);
            } else {
                toast(R.string.isEmptyUrl);
            }

        }
    }, new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isForce) {
                ActivityUtils.closeAll();
            }
        }
    });

After downloading, activate the downloaded apk:

public class DownReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(intent.getAction())) {
        DownloadManager.Query query = new DownloadManager.Query();
        //Get the id of the download task in the broadcast
        long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
        query.setFilterById(id);
        Cursor c = manager.query(query);
        if (c.moveToFirst()) {
            //Get file download path
            //Android 7.0 and above: request to get write permission, and error is reported in this step


            int fileUriIdx = c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
            String fileUri = c.getString(fileUriIdx);
            String fileName = null;
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                if (fileUri != null) {
                    fileName = Uri.parse(fileUri).getPath();
                }
            } else {
                //Obsolete way: downloadmanager.column'local'filename
                int fileNameIdx = c.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
                fileName = c.getString(fileNameIdx);
            }


            if (id == SharedPreferencesUtils.getLong(context, SPKey.APK_DOWN_ID, 0) && !TextUtils.isEmpty(fileName)) {
                //Open APK installation
                installApk(context, fileName);
            } else {
                //If the file name is not empty, it means it already exists. It's good to get the file name
                if (fileName != null) {
                    UIUtils.toast(context, R.string.down_success);
                }
            }
        }
    } else if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(intent.getAction())) {
        long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
        //Click the notice bar to cancel the download
        manager.remove(ids);
        UIUtils.toast(context, R.string.down_cancel);
    }
}

/**
 * Install APK files
 */
public void installApk(Context context, String fileName) {
    ActivityUtils.closeAll();
    File apkfile = new File(fileName);
    if (!apkfile.exists()) {
        return;
    }
    // Installing APK files through Intent
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(i);
}}

Remember to add:

<receiver android:name="com.meiguiyuehui.cn.receivers.DownReceiver">
        <intent-filter>
            <action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
            <action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED" />
        </intent-filter>
    </receiver>

Topics: Android