Android: Stop/Start service depending on WiFi stat

2019-01-21 07:25发布

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 android, and what I've got so far has taken me forever to Achieve, so I'm really hoping for some pointers.

My service is set to start up when the phone starts up. Also when the Activity is launched it checks whether the service is running - and if not it starts it. I'm just wondering what code I can put into my service to make it turn off if the WiFi state is lost - and what code I need to make the service start once a WiFi connection becomes active?

Thanks! :)

4条回答
在下西门庆
2楼-- · 2019-01-21 07:26

You can create a BroadcastReceiver that handles wifi connection changes.

To be more precise, you will want to create a class - say NetWatcher:

public class NetWatcher extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //here, check that the network connection is available. If yes, start your service. If not, stop your service.
       ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
       NetworkInfo info = cm.getActiveNetworkInfo();
       if (info != null) {
           if (info.isConnected()) {
               //start service
               Intent intent = new Intent(context, MyService.class);
               context.startService(intent);
           }
           else {
               //stop service
               Intent intent = new Intent(context, MyService.class);
               context.stopService(intent);
           }
       }
    }
}

(changing MyService to the name of your service).

Also, in your AndroidManifest, you need to add the following lines:

<receiver android:name="com.example.android.NetWatcher">
     <intent-filter>
          <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
     </intent-filter>
</receiver>

(changing com.example.android to the name of your package).

查看更多
女痞
3楼-- · 2019-01-21 07:30

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);
       }
    }

}
查看更多
闹够了就滚
4楼-- · 2019-01-21 07:39

More useful information is provided here: Determining and Monitoring the Connectivity Status

查看更多
甜甜的少女心
5楼-- · 2019-01-21 07:51

As @Phil stated, you should extend BroadcastReceiver, and in onReceive method start or stop the service. Something like:

class ConnectionChangeReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            //start service
        } else {
            //stop service
        }
    }
}

You can make this a private class of your activity, and register receiver on activity create, and unregister it on activity destroy.

查看更多
登录 后发表回答