Android: Stop/Start service depending on WiFi state?

后端 未结 4 716
耶瑟儿~
耶瑟儿~ 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:23

    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.

提交回复
热议问题