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! :)
You can create a BroadcastReceiver that handles wifi connection changes.
To be more precise, you will want to create a class - say NetWatcher:
(changing
MyService
to the name of your service).Also, in your
AndroidManifest
, you need to add the following lines:(changing
com.example.android
to the name of your package).To start/stop your service when supplicant Wifi state is ok/nok:
So register your broadcast receiver to receive
WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION
. Add permissionandroid.permission.CHANGE_WIFI_STATE
orandroid.permission.ACCESS_NETWORK_STATE
. I'm not sure if it is necessary or not.Then a sample broadcast receiver code could be:
More useful information is provided here: Determining and Monitoring the Connectivity Status
As @Phil stated, you should extend BroadcastReceiver, and in onReceive method start or stop the service. Something like:
You can make this a private class of your activity, and register receiver on activity create, and unregister it on activity destroy.