我正在尝试捕获下载完成事件,但我的BroadcastReceiver没有收到它们。这是接收者:
public class DownloadListenerService extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
System.out.println("got here");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = settings.edit();
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
String downloadPath = intent.getStringExtra(DownloadManager.COLUMN_URI);
editor.putString("downloadPath", downloadPath);
editor.commit();
}
}
}
这是清单:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver
android:name="com.example.alreadydownloaded.DownloadListenerService"
android:exported="true">
<intent-filter>
<action android:enabled="true" android:name="android.intent.action.DOWNLOAD_COMPLETE" />
</intent-filter>
</receiver>
</application>
有人看到了什么问题吗?
答案 0 :(得分:16)
com.example.DownloadListenerService
android:exported="true"
BroadcastReceiver
可以从其应用来源outside
接收消息。将Action
中intent-filter
的名称更改为android.intent.action.DOWNLOAD_COMPLETE
<receiver
android:name="com.example.DownloadListenerService"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.INTERNET" />
只有在您的应用程序使用 registerReceiver(@Nullable BroadcastReceiver receiver,IntentFilter filter);
要排队的代码下载:
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse("https://www.google.com/images/srpr/logo4w.png"));
dm.enqueue(request);
答案 1 :(得分:0)
我认为XML中的操作名称是错误的。文档说明正确的是: android.intent.action.DOWNLOAD_COMPLETE 而非 DownloadManager.ACTION_DOWNLOAD_COMPLETE - 您需要使用常量,而不是Java表单。
<receiver android:name=".DownloadListenerService" >
<intent-filter>
<action android:enabled="true" android:name="android.intent.action.DOWNLOAD_COMPLETE" />
</intent-filter>
</receiver>
答案 2 :(得分:0)
<receiver
android:name=".BroadCast_Service.Download_BroadCast"
android:exported="true">
<intent-filter android:priority="1099">
<action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
</intent-filter>
</receiver>
答案 3 :(得分:-1)
我认为您是从IntentService / Service调用DownloadManger服务。如果是这样,将其从那里移除并将其投入活动。
在android清单中添加权限
<uses-permission android:name="android.permission.SEND_DOWNLOAD_COMPLETED_INTENTS" />
答案 4 :(得分:-4)
如果下载基于您的应用,那么您需要发送广播吗?
Intent i = new Intent();
i.setAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
sendBroadcast(i);