一、添加权限
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission Android:name="android.permission.ACCESS_NETWORK_STATE" />
二、注册监听广播
注册监听有两种方式
1.AndroidMainfest.xml 中注册
<receiver android:name="com.receiver.WifiReceiver">
<intent-filter >
<action android:name="android.net.wifi.RSSI_CHANGED"/>
<action android:name="android.net.wifi.STATE_CHANGE"/>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED"/>
</intent-filter>
</receiver>
2.在代码中注册
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(new WifiReceiver(), filter);
三、实现监听广播类
public class WifiReceiver extends BroadcastReceiver {
private static final String TAG = "wifiReceiver";
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(WifiManager.RSSI_CHANGED_ACTION)) {
Log.i(TAG, "wifi信号强度变化");
}
//wifi连接上与否
if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
Log.i(TAG, "wifi断开");
} else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
//获取当前wifi名称
Log.i(TAG, "连接到网络 " + wifiInfo.getSSID());
TtsManager ttsManager = new TtsManager();
ttsManager.checkTtsJet(context.getApplicationContext());
}
}
//wifi打开与否
if (intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
int wifistate = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_DISABLED);
if (wifistate == WifiManager.WIFI_STATE_DISABLED) {
Log.i(TAG, "系统关闭wifi");
} else if (wifistate == WifiManager.WIFI_STATE_ENABLED) {
Log.i(TAG, "系统开启wifi");
}
}
}
}
写文章不易,路过的伙伴辛苦点个赞,谢谢支持!