Android: Stop/Start service depending on WiFi state?

后端 未结 4 718
耶瑟儿~
耶瑟儿~ 2020-12-12 19:59

In the android application that I\'m designing, my service only needs to be running when the device is connected to the router (via WiFi obviously). I\'m really new to andro

4条回答
  •  眼角桃花
    2020-12-12 20:19

    To start/stop your service when supplicant Wifi state is ok/nok:

    • register a BroadcastReceiver to recieve WIFI state change broadcasted intents
    • inside your BroadCastReceiver check the intent validity then start your service

    So register your broadcast receiver to receive WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION. Add permission android.permission.CHANGE_WIFI_STATE or android.permission.ACCESS_NETWORK_STATE. I'm not sure if it is necessary or not.

    Then a sample broadcast receiver code could be:

    public class MyWifiStatereceiver extends BroadcastReceiver {
        //Other stuff here 
    
        @Override
        public void onReceive(Context context, Intent intent) {
           Intent srvIntent = new Intent();
           srvIntent.setClass(MyService.class);
           boolean bWifiStateOk = false;
    
           if (WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION.equals(intent.getAction()) {
               //check intents and service to know if all is ok then set bWifiStateOk accordingly
               bWifiStateOk = ... 
           } else {
               return ; // do nothing ... we're not in good intent context doh !
           }
    
           if (bWifiStateOk) {
               context.startService(srvIntent);
           } else {
               context.stopService(srvIntent);
           }
        }
    
    }
    

提交回复
热议问题