我从SD卡读取文件,并在Gridview上显示。
当我从Gridview
中选择项目并获取项目的position
时。
我点击下载按钮,它将下载该项目。
如何在使用downloadManager
时停止项目下载?
代码下载按钮如下:
FileNode file = mFileList.get(temp_position) ;//Get the item I have select from Gridview
final String filename = file.mName.substring(file.mName.lastIndexOf("/") + 1) ;
final String urlString = "http://" + mIp + file.mName ;
String serviceString = Context.DOWNLOAD_SERVICE ;
DownloadManager downloadManager ;
downloadManager = (DownloadManager) getActivity().getSystemService(
serviceString) ;
Uri uri = Uri.parse(urlString) ;
DownloadManager.Request request = new Request(uri) ;
request.setTitle(filename) ;
request.setDescription(urlString) ;
String ext = filename.substring(filename.lastIndexOf(".") + 1)
.toLowerCase(Locale.US) ;
String mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(ext) ;
Log.i("MIME", ext + " ==> " + mimeType) ;
if (mimeType != null) {
request.setMimeType(mimeType) ;
}
request.allowScanningByMediaScanner() ;
request.setNotificationVisibility(Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED) ;
request.setDestinationInExternalPublicDir(MainActivity.sAppName, filename) ;
downloadManager.enqueue(request) ;
如何在下载文件时停止项目下载?
答案 0 :(得分:9)
DownloadManager#enqueue
返回long
,代表发生下载的id
。将long
保存在变量中。
然后,如果您需要取消下载,请拨打DownloadManager#remove()
传递那么久。
例如
//start a download
long id = downloadManager.enqueue(request);
//stop a download
downloadManager.remove(id);
答案 1 :(得分:1)
首先在long id
shared preferences
下载请求
像这样
SharedPreferences preferenceManager = PreferenceManager.getDefaultSharedPreferences(ACTIVITY CONTEXT);
Editor PrefEdit = preferenceManager.edit();
PrefEdit.putLong("Download_ID", id);
PrefEdit.commit();
现在编写一个自定义broadcast receiver
,它会收听点击最近开始的下载。
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);
}
}
}
并在Android Manifest
中注册您的广播接收器
<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>