我的应用程序需要知道用户何时打开或关闭了Wifi或移动数据。实际上它显示网络何时发生变化,如果设备有连接,则工作正常。但是当用户手动打开/关闭网络时我想知道。
知道我在Manifest上有这个。
<receiver android:name="pe.com.gps.broadcastreceivers.CheckForMobileDataBroadcastReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
答案 0 :(得分:2)
在onCreate方法中(或者只要您想知道wifi是否已连接),请使用 WifiManager 。例如:
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
}
在这种情况下, ConnectivityManager 也可以为您提供帮助。请检查此conversation.
答案 1 :(得分:0)
更改网络后,CheckForMobileDataBroadcastReceiver将收到连接已更改的广播消息。收到该消息后,您可以查询当前的网络状态。如果您查看android文档中的this文章,它会详细介绍如何访问活动网络。
答案 2 :(得分:0)
function sample () { // code goes here }