qq群:614530228
- 首先在清单文件里加入权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
- NetworkChangeReceiver.class
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (null != networkInfo && networkInfo.isAvailable()) {
switch (networkInfo.getType()) {
case ConnectivityManager.TYPE_MOBILE:
Toast.makeText(context, "正在使用2G/3G/4G网络", Toast.LENGTH_SHORT).show();
break;
case ConnectivityManager.TYPE_WIFI:
Toast.makeText(context, "正在使用wifi上网", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
} else {
Toast.makeText(context, "当前网络不可用", Toast.LENGTH_SHORT).show();
}
}
}
- 在BaseApp.class中注册广播
public class BaseApp extends Application {
private NetworkChangeReceiver receiver;
@Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
receiver = new NetworkChangeReceiver();
registerReceiver(receiver, filter);
}
@Override
public void onLowMemory() {
super.onLowMemory();
if (null != receiver) {
unregisterReceiver(receiver);
}
}
}
网友评论