public class NetworkStateReceiver extends BroadcastReceiver {
private NetworkStateListener mNetworkStateListener = BaseActivity.networkStateListener;
/**
* 没有网络
*/
private static final int NETWORK_NONE = -1;
/**
* 移动网络
*/
private static final int NETWORK_MOBILE = 0;
/**
* 无线网络
*/
private static final int NETWORK_WIFI = 1;
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// 如果相等的话就说明网络状态发生了变化
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
//得到连接管理器对象
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
//如果网络连接,判断该网络类型
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
//连接状态
//BaseActivity.NETWORK_LAST_TYPE这里不会改变成员变量的值,所有定义在BaseActivity里
if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
if (BaseActivity.NETWORK_LAST_TYPE != NETWORK_WIFI) {//避免多次调用
if (mNetworkStateListener != null)
mNetworkStateListener.onNetworkStateListener(NETWORK_WIFI);
}
BaseActivity.NETWORK_LAST_TYPE = 1;
} else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
if (BaseActivity.NETWORK_LAST_TYPE != NETWORK_MOBILE) {
if (mNetworkStateListener != null)
mNetworkStateListener.onNetworkStateListener(NETWORK_MOBILE);
}
BaseActivity.NETWORK_LAST_TYPE = 0;
}
} else {
//网络断开回调
if (BaseActivity.NETWORK_LAST_TYPE == 1) {//无线网络
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if (BaseActivity.NETWORK_LAST_TYPE != NETWORK_MOBILE) {
if (mNetworkStateListener != null) {
mNetworkStateListener.onNetworkStateListener(NETWORK_NONE);
BaseActivity.NETWORK_LAST_TYPE = -1;
}
}
}
}, 300);
} else {//移动网络
if (BaseActivity.NETWORK_LAST_TYPE != NETWORK_NONE) {
if (mNetworkStateListener != null)
mNetworkStateListener.onNetworkStateListener(NETWORK_NONE);
}
BaseActivity.NETWORK_LAST_TYPE = -1;
}
}
}
}
// 自定义接口
public interface NetworkStateListener {
/**
* -1 没有网络 0 移动网络 1wifi
*
* @param status
*/
void onNetworkStateListener(int status);
}
}
在BaseActivity里实现变化接口:
public abstract class BaseActivity extends AppCompatActivity implements NetworkStateReceiver.NetworkStateListener {
public static NetworkStateReceiver.NetworkStateListener networkStateListener;
/**
* 最后一次获取网络类型
*/
public static int NETWORK_LAST_TYPE = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
networkStateListener = this;
}
@Override
public void onNetworkStateListener(int status) {
switch (status) {
case -1:
ToastUtils.showShort("当前无网络");
break;
case 0:
ToastUtils.showShort("当前使用移动数据");
break;
case 1:
ToastUtils.showShort("当前使用WIFI数据");
break;
}
}