@@ -508,6 +508,10 @@ public class WifiManager {
508508 private Messenger mWifiServiceMessenger ;
509509 private final CountDownLatch mConnected = new CountDownLatch (1 );
510510
511+ private static Object sThreadRefLock = new Object ();
512+ private static int sThreadRefCount ;
513+ private static HandlerThread sHandlerThread ;
514+
511515 /**
512516 * Create a new WifiManager instance.
513517 * Applications will almost always want to use
@@ -1365,9 +1369,14 @@ private void init() {
13651369 return ;
13661370 }
13671371
1368- HandlerThread t = new HandlerThread ("WifiManager" );
1369- t .start ();
1370- mHandler = new ServiceHandler (t .getLooper ());
1372+ synchronized (sThreadRefLock ) {
1373+ if (++sThreadRefCount == 1 ) {
1374+ sHandlerThread = new HandlerThread ("WifiManager" );
1375+ sHandlerThread .start ();
1376+ }
1377+ }
1378+
1379+ mHandler = new ServiceHandler (sHandlerThread .getLooper ());
13711380 mAsyncChannel .connect (mContext , mHandler , mWifiServiceMessenger );
13721381 try {
13731382 mConnected .await ();
@@ -1983,8 +1992,10 @@ public void captivePortalCheckComplete() {
19831992
19841993 protected void finalize () throws Throwable {
19851994 try {
1986- if (mHandler != null && mHandler .getLooper () != null ) {
1987- mHandler .getLooper ().quit ();
1995+ synchronized (sThreadRefLock ) {
1996+ if (--sThreadRefCount == 0 && sHandlerThread != null ) {
1997+ sHandlerThread .getLooper ().quit ();
1998+ }
19881999 }
19892000 } finally {
19902001 super .finalize ();
0 commit comments