cache and database consistency solution

2023-01-23   ES  

This article is Marno Original

Reprinted address (

Write nonsense in front

download files, almost all apps that can be used in all apps! Forget it, let’s not talk nonsense, just write it directly. Essence Essence

Simple use

to complete a download task only requires 4 lines. What breakpoints are passed, large file downloads, and the progress of the notification column shows … You don’t need to worry about it.

// Create the download task, downloadurl is the download link
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(downloadUrl));
// Specify the download path and download file name
request.setDestinationInExternalPublicDir("/download/", fileName);
// Get the download manager
DownloadManager downloadManager= (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
// Add the download task to the download queue, otherwise you will not download
Advanced usage
  • Everyone can also see through the code above. We use the download manager provided by the system to download, and we start supporting from API 9, so don’t worry about compatible issues
  • Since it is provided by the system, there must be more powerful usage, the article continues

Let us see the source code of DOWNLOADMANAGER, which provides so many methods

download method

downloadmanager.request method


  • method is almost all of which, which is relatively complete, which can meet most of our usage scenarios.
Actual use

Next, we will use the app application to update as an example. Let’s talk about the use of these methods
1. First of all, we sort out the logic of updated in the app application

app application internal update

2. Next, look at the specific implementation, code

// Use the system downloader to download
private void downloadAPK(String versionUrl, String versionName) {
        // Create a download task
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(versionUrl));
        request.setAllowedOverRoaming(false);// Whether the roaming network can download

        // Set the file type, you can automatically open the file after downloading
        MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
        String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(versionUrl));

        // In the notification column, the default is displayed

        // DOWNload folder in the directory of sdcard must be set
        request.setDestinationInExternalPublicDir("/download/", versionName);
        //request.SetDestInationineXternalfilesdir (), you can also formulate the download path by yourself

        // Add the download request to the download queue
        downloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        // After joining the download queue, you will return a LONG type ID to the task.
        // Through this ID, you can cancel the task, restart the task, etc., and look at the method frame in the source code above
        mTaskId = downloadManager.enqueue(request);

        // Register a broadcast receiver, monitor the download status
                new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

The next is the broadcast receiver

    // Broadcast recipient, receive download status
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            checkDownloadStatus();// Check the download status

Check the download status

 // Check the download status
    private void checkDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(mTaskId);// Filter the download task, pass the task ID, variable parameters
        Cursor c = downloadManager.query(query);
        if (c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch (status) {
                case DownloadManager.STATUS_PAUSED:
                    MLog.i(">>> Download pause");
                case DownloadManager.STATUS_PENDING:
                    MLog.i(">>> download delay");
                case DownloadManager.STATUS_RUNNING:
                    MLog.i(">>> downloading");
                case DownloadManager.STATUS_SUCCESSFUL
                    MLog.i(">>> Download the complete");
                    // Download the installation APK
                    //downloadPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + versionName;
                    installAPK(new File(downloadPath));
                case DownloadManager.STATUS_FAILED:
                    MLog.i(">>> download failed");

Install APK

    // Download it locally and perform installation
    protected void installAPK(File file) {
        if (!file.exists()) return;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.parse("file://" + file.toString());
        intent.setDataAndType(uri, "application/");
        // In the service, you must set FLAG when you open the Activity in the service, and explain later

At this point, the code for updating the app in the application is completed, but there are some pits to pay attention!

I hope you can see the last few sentences, otherwise you will be pitted!

1. Although you don’t need to worry about downloading, it is recommended to put the entire four -paragraph code in the service, because when placed in Activity, when the user presses the Home button, even if the download is finished, it will not. Pop -up installation interface
2. It is recommended to use the Startservice method to start the service, so that it will not be bound to the Activity cycle to ensure that it can be installed smoothly after the download.
3.Service to stop after use!

Wen / Marno (Author of Jane)
Original link:
Copyright belongs to the author, please contact the author to obtain authorization and mark the “Jianshu Author”.


Related Posts

Learning rate (adjustment step) ITER =

CSS Learning Notes | CSS background

Luolai Family Textiles grant customer reward points shall be treated with deferred income method

Solving the Mu class linux tutorial xshell cannot connect CentOS, VMware Install CentOS6.3, connect xshell

cache and database consistency solution

Random Posts

Why is the data in the data so important? Mingluo Technology Wu Xindong: The source of the core competitiveness of the company in the intelligent era | Meet2020 …

HDU1426 Sudoku Killer

About the Input box defaultValue in Antd-Desgin-Vue

Detailed explanation: nested problems of pointers, array and functions

jqgrid Learning note 03 View selection items, control a line of selection or not outside the territory