<receiver android:name=".receiver.NetBroadcastReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
public class NetBroadcastReceiver extends BroadcastReceiver {
/**
* 只有当网络改变的时候才会 经过广播。
*/
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
NetUtil.getNetInfo(context);
}
}
}
* 判断网络工具类
*/
public class NetUtil {
/**
* 没有连接网络
*/
private static final int NETWORK_NONE = -1;
/**
* 移动网络
*/
private static final int NETWORK_MOBILE = 0;
/**
* 无线网络
*/
private static final int NETWORK_WIFI = 1;
public static int getNetWorkState(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {
return NETWORK_WIFI;
} else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {
return NETWORK_MOBILE;
}
} else {
return NETWORK_NONE;
}
return NETWORK_NONE;
}
public static void getNetInfo(Context context) {
int netWorkState =getNetWorkState(context);
if (netWorkState == 1) {
System.out.println("wifi已连接");
ToastUtils.showToast("wifi已连接");
} else if (netWorkState == 0) {
System.out.println("移动数据已连接");
ToastUtils.showToast("移动数据已连接");
} else if (netWorkState == -1) {
System.out.println("网络已断开");
ToastUtils.showToast("网络已断开");
}
}
}