Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WifiManager Thread never shuts down

After executing this line:

WifiManager man = ((WifiManager) ctx.getSystemService(Context.WIFI_SERVICE));

A thread labeled "WifiManager" will show up. In the Java source file for WifiService.java line 203:

 HandlerThread wifiThread = new HandlerThread("WifiService");
 wifiThread.start();
 mWifiHandler = new WifiHandler(wifiThread.getLooper());

Problem is, every time our app is closed and reopened it creates a new thread, run it 5 times and you have 5 threads. Not sure if there is anyway to stop it?

EDIT

Changed to getApplicationContext to make sure the context it was accessing was consistent and all was well. I still get a thread labeled "WifiService," but I only get one thread over multiple runs.

like image 650
accordionfolder Avatar asked Dec 06 '12 19:12

accordionfolder


2 Answers

I believe you are creating a new WifiManager in your started/stopped (Context) Activity.

A note from Context.getSystemService()

Note: System services obtained via this API may be closely associated with the Context in which they are obtained from. ...

Also from ContextImpl.java:1478 and :227

@Override
public Object getSystemService(String name) {
    ServiceFetcher fetcher = SYSTEM_SERVICE_MAP.get(name);
    return fetcher == null ? null : fetcher.getService(this);
}



...
service = cache.get(mContextCacheIndex);
if (service != null) {
    return service;
}
...

It uses a map to cache system services, so I believe if you use the same context like Application, you wouldn't run into this problem. I am not sure if this is the right way of solving this problem however, if having threads laying around a bigger issue for you, it may worth while.

like image 200
auselen Avatar answered Sep 27 '22 20:09

auselen


When you get the instance of a system service using Context.getSystemService(), you are not calling the constructor of the service. Instead, you are actually getting an instance of the service using IBinder so as to do a remote procedure call on it. So the constructor of WiFiService.java will not be called every time you get an instance of it. Where exactly are you seeing this thread pop up?

like image 32
StarNix Avatar answered Sep 27 '22 19:09

StarNix