Search code examples
androidservicewifi

Android: Stop/Start service depending on WiFi state?


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! :)


Solution

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