Broadcast Receiver in IntentService (Service has leaked IntentReceiver)
I try to implement an IntentService
with a BroadcastReceiver
that reacts on the SCAN_RESULTS_AVAILABLE_ACTION
.
The IntentService
is supposed to compare Lists whenever onReceive
is called. I always get the
"Service has leaked IntentReceiver"
error even though I unregister the BroadcastReceiver
in onDestroy()
.
Here is the code:
public class MyClass extends IntentService {
private HashMap<String, List<String>>;
private WifiManager mWifiManager;
private WifiReceiver mWifiReceiver;
public MyClass() {
super("MyClass");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
mWifiReceiver = new WifiReceiver();
registerReceiver(mWifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
mWifiManager.createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY,"ScanLock");
mWifiManager.setWifiEnabled(true);
return START_NOT_STICKY;
}
@Override
public void onDestroy(){
unregisterReceiver(mWifiReceiver);
mWifiManager.setWifiEnabled(false);
}
@Override
protected void onHandleIntent(Intent intent) {
开发者_运维百科// TODO Auto-generated method stub
}
class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//Here I do my stuff with the scan results
//should be called every 5 seconds
}
}
Where is the problem in the code?
Why do I keep getting this error?
I still have to learn a lot about Android, but I think the IntentService
is the right way to go since I do not expect any result from this class. It should just stop when I send a call stopService()
. This IntentService
is called by another IntentService
! Is that a problem?
Thanks for helping.
I try to implement an IntentService with a BroadcastReceiver that reacts on the SCAN_RESULTS_AVAILABLE_ACTION.
This is largely pointless. Your receiver will be registered for a few seconds at most, hopefully.
I still have to learn a lot about Android, but I think the IntentService is the right way to go since I do not expect any result from this class.
That makes no sense whatsoever. You use an IntentService
when you have a short bit of work that needs to be performed in a background thread. For example, if you use AlarmManager
to check for new email messages every 15 minutes, or you have an activity kick off a large file download, you would use IntentService
.
It should just stop when I send a call stopService().
You never call stopService()
on an IntentService
. The IntentService
stops itself once onHandleIntent()
returns. This is why your BroadcastReceiver
will be removed within seconds -- your onHandleIntent()
should only be running for seconds.
This IntentService is called by another IntentService!
This is unlikely to be a good design.
Try registering BroadcastReceiver
in OnCreate()
instead of OnStartCommand()
,
That should fix your problem.
精彩评论