public class NetworkConnectChangedReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {//這個監聽wifi的打開與關閉,與wifi的鏈接無關
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
LogTag.showTAG_e("WIFI狀態", "wifiState"+wifiState);
switch (wifiState) {
case WifiManager.WIFI_STATE_DISABLED:
break;
case WifiManager.WIFI_STATE_DISABLING:
break;
//
}
}
// 這個監聽wifi的鏈接狀態便是否連上了一個有效無線路由,當上邊廣播的狀態是WifiManager.WIFI_STATE_DISABLING,和WIFI_STATE_DISABLED的時候,根本不會接到這個廣播。
// 在上邊廣播接到廣播是WifiManager.WIFI_STATE_ENABLED狀態的同時也會接到這個廣播,固然剛打開wifi確定尚未鏈接到有效的無線
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {
Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (null != parcelableExtra) {
NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;
State state = networkInfo.getState();
boolean isConnected = state==State.CONNECTED;//固然,這邊能夠更精確的肯定狀態
LogTag.showTAG_e(this.getClass().getSimpleName(), "isConnected"+isConnected);
if(isConnected){
}else{
}
}
}
//這個監聽網絡鏈接的設置,包括wifi和移動數據的打開和關閉。.
//最好用的仍是這個監聽。wifi若是打開,關閉,以及鏈接上可用的鏈接都會接到監聽。見log
// 這個廣播的最大弊端是比上邊兩個廣播的反應要慢,若是隻是要監聽wifi,我以爲仍是用上邊兩個配合比較合適
if(ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())){
NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (info != null) {
LogTag.showTAG_e("CONNECTIVITY_ACTION", "info.getTypeName()"+info.getTypeName());
LogTag.showTAG_e("CONNECTIVITY_ACTION", "getSubtypeName()"+info.getSubtypeName());
LogTag.showTAG_e("CONNECTIVITY_ACTION", "getState()"+info.getState());
LogTag.showTAG_e("CONNECTIVITY_ACTION",
"getDetailedState()"+info.getDetailedState().name());
LogTag.showTAG_e("CONNECTIVITY_ACTION", "getDetailedState()"+info.getExtraInfo());
LogTag.showTAG_e("CONNECTIVITY_ACTION", "getType()"+info.getType());
}
} 網絡
if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(intent.getAction())) {// 這個監聽wifi的鏈接狀態
Parcelable parcelableExtra = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (null != parcelableExtra) {
NetworkInfo networkInfo = (NetworkInfo) parcelableExtra;
State state = networkInfo.getState();
if(state==State.CONNECTED){
showWifiCconnected(context);
}
/**else if(state==State.DISCONNECTED){
showWifiDisconnected(context);
}*///昨天寫的這個方法,在坐地鐵的時候發現,若是地鐵上有無效的wifi站點,手機會自動鏈接,可是鏈接失敗後仍是會接到廣播,因此不能用了
}
}
if(ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())){//這個監聽網絡鏈接的設置,包括wifi和移動數據 的打開和關閉
NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (info != null) {
if(NetworkInfo.State.CONNECTED==info.getState()){
Intent pushIntent = new Intent();
pushIntent.setClass(context, NotificationService.class);
}else if(info.getType()==1){
if(NetworkInfo.State.DISCONNECTING==info.getState())
showWifiDisconnected(context);
}
}
}
} ide