Android 来自IntentService的registerReceiver不';t命中广播接收机
我创建了一个Android 来自IntentService的registerReceiver不';t命中广播接收机,android,broadcastreceiver,android-service,android-download-manager,Android,Broadcastreceiver,Android Service,Android Download Manager,我创建了一个IntentService,用于使用Android的DownloadManager下载文件。以下是我的班级: public class DownloadService extends IntentService { public DownloadService() { super("name"); } BroadcastReceiver onComplete = new BroadcastReceiver() { public
IntentService
,用于使用Android的DownloadManager下载文件。以下是我的班级:
public class DownloadService extends IntentService {
public DownloadService() {
super("name");
}
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
function();
}
};
@Override
protected void onHandleIntent(Intent intent) {
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
Utility.download(someURL);
}
}
我在舱单中有此条目:
<service
android:name=".services.DownloadService"
android:enabled="true" >
</service>
BroadcastReceiver(function())
中的代码永远不会执行,即使文件已下载。我也试着在服务
中做同样的事情,而不是IntentService
,它成功了。
如何使BroadcastReceiver在IntentService内部工作?避免使用IntentService的上下文调用
registerReceiver
方法
方法返回后,将调用该方法。所有尚未注册的接收器都将被视为泄漏。该框架甚至警告您:
E/ActivityThread﹕ Service com.your.packagename.YourIntentService has leaked IntentReceiver com.your.packagename.YourReceiver@41f4cd08 that was originally registered here. Are you missing a call to unregisterReceiver()?
android.app.IntentReceiverLeaked: Service com.your.packagename.YourIntentService has leaked IntentReceiver com.your.packagename.YourReceiver@41f4cd08 that was originally registered here. Are you missing a call to unregisterReceiver()?
at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:796)
at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:597)
at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1438)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1418)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1412)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:467)
at com.your.packagename.YourIntentService.onHandleIntent(YourIntentService.java:79)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.os.HandlerThread.run(HandlerThread.java:61)
但是请注意,您必须添加逻辑,一旦完成注册,就会注销每个此类接收器实例。我认为您需要在android清单中注册广播接收器,而不是通过编程进行设置。系统需要知道你的应用程序可以处理DownloadManager.ACTION\u DOWNLOAD\u COMPLETE Intents如果我希望注册的接收者在应用程序关闭后被触发,你会有什么建议。如果我使用getApplication context,它将不会被触发。@AraYeressian您可以在清单中声明您的接收器,并根据您的逻辑使用
getApplication().registerReceiver(receiverInstance,
new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));