Update DownloadManager usage with android system

The results are as follows:




added in API level 9.

Package path:
java.lang.Object
   ↳ android.app.DownloadManager
Download Manager is a system service that handles long-running HTTP downloads. Applications requested to download through this API should be ACTION_NOTIFICATION_CLICKED registers a broadcast receiver so that the user clicks on a running download in the notification or handles it correctly from the download UI.

Instances of this class must useContext.getSystemService(Class), parameter is DownloadManager.class orContext.getSystemService(String), parameter is Context.DOWNLOAD_SERVICE.

Note: The following two permissions need to be added when using

a. Network access <uses-permission android:name="android.permission.INTERNET" />

b. Write permissions for external storage <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />


The main steps of this routine are:

1. Add permissions and configure broadcast receivers (for receiving system broadcasts when clicks and downloads are complete)

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<receiver android:name=".receiver.DownloadReceiver">
            <intent-filter>
                <action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
                <action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED" />
            </intent-filter>
        </receiver>
2. Responses to click events and download completion events are mainly implemented in the broadcast receiver; that is, Click to jump to the Download View page when incomplete, and automatically invoke the installation application when complete.

public class DownloadReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
            long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            installApk(context, id);
        } else if (intent.getAction().equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
            // DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            //Get all download task Ids groups
            //long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
            ////Click on the notification bar to cancel all downloads
            //manager.remove(ids);
            //Toast.makeText(context,'download task cancelled',Toast.LENGTH_SHORT).show();
            //Processing If the download has not been completed, the user clicks Notification and jumps to the download center
            Intent viewDownloadIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
            viewDownloadIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(viewDownloadIntent);
        }
    }

    private static void installApk(Context context, long downloadApkId) {
        DownloadManager dManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Intent install = new Intent(Intent.ACTION_VIEW);
        Uri downloadFileUri = dManager.getUriForDownloadedFile(downloadApkId);
        if (downloadFileUri != null) {
            Log.d("DownloadManager", downloadFileUri.toString());
            install.setDataAndType(downloadFileUri, "application/vnd.android.package-archive");
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(install);
        } else {
            Log.e("DownloadManager", "download error");
        }
    }

3. Call update operation in Activity
public class MainActivity extends AppCompatActivity {

    private String url = "https://downpack.baidu.com/appsearch_AndroidPhone_v8.0.3(1.0.65.172)_1012271b.apk";
    private String title = "Test Application.apk";
    private String desc = "When the download is complete, click Install";

    private Button btn;
    private DownloadManagerUtil downloadManagerUtil;

    long downloadId = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViews();
        initView();
    }

    private void findViews() {
        btn = findViewById(R.id.btn);
    }

    private void initView() {
        downloadManagerUtil = new DownloadManagerUtil(this);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (downloadId != 0) {
                    adownloadManagerUtil.clearCurrentTask(downloadId);
                }
                downloadId = downloadManagerUtil.download(url, title, desc);
            }
        });
    }

4. Download the tool class DownloadManagerUtil, which mainly completes the parameter setting of DownloadManager and launches the download task

public class DownloadManagerUtil {
    private Context mContext;

    public DownloadManagerUtil(Context context) {
        mContext = context;
    }

    public long download(String url, String title, String desc) {
        Uri uri = Uri.parse(url);
        DownloadManager.Request req = new DownloadManager.Request(uri);
        //Update under set WIFI
        req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        //Show notification bar during and after download
        req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        //Use the system default download path Here is in-app/android/data/packages, so compatible with 7.0
        req.setDestinationInExternalFilesDir(mContext, Environment.DIRECTORY_DOWNLOADS, title);
        //Notification Bar Title
        req.setTitle(title);
        //Notification Bar Description Information
        req.setDescription(desc);
        //Set type to.apk
        req.setMimeType("application/vnd.android.package-archive");
        //Get Download Task ID
        DownloadManager dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        return dm.enqueue(req);
    }

    /**
     * Remove the previous task before downloading to prevent duplicate Downloads
     * @param downloadId
     */
    public void clearCurrentTask(long downloadId) {
        DownloadManager dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        try {
            dm.remove(downloadId);
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        }
    }



Tags: Android Java network

Posted on Sat, 04 Jul 2020 11:06:01 -0400 by Citizen