How to stop the file download in android by using DownloadManager?

荒凉一梦 提交于 2019-12-06 14:06:17

DownloadManager#enqueue returns a long representing the id of the download taking place. Save that long in a variable.

Then, if you need to cancel the download, call DownloadManager#remove() passing in that long.

Eg

//start a download
long id = downloadManager.enqueue(request);

//stop a download
downloadManager.remove(id);

first of all save the long id of download request in shared preferences

like this

SharedPreferences preferenceManager = PreferenceManager.getDefaultSharedPreferences(ACTIVITY CONTEXT);
    Editor PrefEdit = preferenceManager.edit();
    PrefEdit.putLong("Download_ID", id);
    PrefEdit.commit();

now write a custom broadcast receiver which will listen to click on recently started download.

    public class DownloadManagerBR extends BroadcastReceiver {
        DownloadManager down_m ;
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            down_m = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
            SharedPreferences preferenceManager 
            = PreferenceManager.getDefaultSharedPreferences(context);
            long id = preferenceManager.getLong("Download_ID", 0);
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {

            }
            else if (DownloadManager.ACTION_NOTIFICATION_CLICKED.equals(action)) {
            //IN THIS SECTION YOU CAN WRITE YOUR LOGIC TO CANCEL DOWNLOAD AS STATED IN ABOVE ANSWER 
              downloadManager.remove(id);
            }
        }
    } 

and register your broadcast receiver in Android Manifest like this

<receiver android:name=".DownloadManagerBR" >
            <intent-filter>
                <action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
                <action android:name="android.intent.action.DOWNLOAD_NOTIFICATION_CLICKED" />
            </intent-filter>
        </receiver>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!