这是我的广播接收器:
BroadcastReceiver broadcast = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
dwnId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Cursor c = DownloadManagerWrapper.getInstance(getActivity()).getDownloadManager().query(new DownloadManager.Query().setFilterById(dwnId));
c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
} else {
Toast.makeText(getActivity(), "ERROR!", Toast.LENGTH_SHORT).show();
}
}
};
在我的onCreateView上我注册它:
(getActivity()).registerReceiver(broadcast, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
这就是我的DownloadManagerWrapper的样子:
public class DownloadManagerWrapper {
private static final String DOWNLOAD_SERVICE = "download";
private DownloadManager mgr;
private static DownloadManagerWrapper i;
private DownloadManagerWrapper(Context c) {
mgr = (DownloadManager) c.getSystemService(DOWNLOAD_SERVICE);
}
public static DownloadManagerWrapper getInstance(Context c) {
if (i == null) {
i = new DownloadManagerWrapper(c);
}
return i;
}
public DownloadManager getDownloadManager() {
return mgr;
}
}
这就是我所做的,使它成为FC:
if(Util.hasNetworkConnection(ctx)){
Uri destination = Uri.parse("file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/media/video.mp4");
DownloadManagerWrapper.getInstance(ctx).getDownloadManager().enqueue(new DownloadManager.Request(uri).setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE).setAllowedOverRoaming(false).setDestinationUri(destination));
}else{
Toast.makeText(ctx, "No Internet Available!!", Toast.LENGTH_SHORT).show();
}
我得到这个错误:
02-14 15:57:03.488: E/AndroidRuntime(4987): FATAL EXCEPTION: main
02-14 15:57:03.488: E/AndroidRuntime(4987): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.DOWNLOAD_COMPLETE flg=0x10 pkg=com.Red.medicalpaint (has extras) } in com.Red.Fragments.AppLibraryFragment$1@41a1f998
02-14 15:57:03.488: E/AndroidRuntime(4987): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:765)
02-14 15:57:03.488: E/AndroidRuntime(4987): at android.os.Handler.handleCallback(Handler.java:615)
02-14 15:57:03.488: E/AndroidRuntime(4987): at android.os.Handler.dispatchMessage(Handler.java:92)
02-14 15:57:03.488: E/AndroidRuntime(4987): at android.os.Looper.loop(Looper.java:137)
02-14 15:57:03.488: E/AndroidRuntime(4987): at android.app.ActivityThread.main(ActivityThread.java:4978)
02-14 15:57:03.488: E/AndroidRuntime(4987): at java.lang.reflect.Method.invokeNative(Native Method)
评论这一行,使其发挥作用:
c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));