Search code examples
javaandroidandroid-wifi

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.


Solution

  • 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.