How to know when the user turn on/off mobile data or wifi?

雨燕双飞 提交于 2019-12-11 02:55:44

问题


My application needs to know when the Wifi or the Mobile data has been turned on or off by the user. Actually it shows when the network changes, if the device has connection or not, works fine. but I want to konw when the user is turning on/off the network manually.

Right know I have this on my Manifest.

<receiver android:name="pe.com.gps.broadcastreceivers.CheckForMobileDataBroadcastReceiver" >
       <intent-filter>
           <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
       </intent-filter>
   </receiver>   

回答1:


In onCreate method (or whenever you want to know that wifi is connected or not) use WifiManager . For example:

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);

if (!wm.isWifiEnabled()) {
   // wm.setWifiEnabled(true);
   //Or do what you want in disable mode
} else {
    // wm.setWifiEnabled(false);
    //Or do what you want in enable mode
}

In this case ConnectivityManager also help you. Check this conversation.




回答2:


When the network is changed, your CheckForMobileDataBroadcastReceiver will receive the broadcast message that the connection has changed. Once you receive that message, you can query the current network state. If you take a look at this article in the android documentation it details how you can access the active network.

ConnectivityManager has constants for Mobile/Wifi etc which can be used for comparing against the network to figure out its type.




回答3:


WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
if (!wifiManager.isWifiEnabled())Toast.makeText(this, "Wifi is not enabled", Toast.LENGTH_SHORT).show();


来源:https://stackoverflow.com/questions/21409169/how-to-know-when-the-user-turn-on-off-mobile-data-or-wifi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!