1. 新建一个基类BasicActivity.class,在基类中注册网络监听广播NetworkChangeReceiver.class,所有页面的Activity都继承此基类BasicActivity.class
(1)网络状态改变监听类:NetWorkChangReceiver.class
/** * 监听网络状态变化 * Created by Travis on 2017/10/11. */public class NetWorkChangReceiver extends BroadcastReceiver { /** * 获取连接类型 * * @param type * @return */ private String getConnectionType(int type) { String connType = ""; if (type == ConnectivityManager.TYPE_MOBILE) { connType = "3G网络数据"; } else if (type == ConnectivityManager.TYPE_WIFI) { connType = "WIFI网络"; } return connType; } @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); Log.e("TAG", "wifiState:" + wifiState); switch (wifiState) { case WifiManager.WIFI_STATE_DISABLED: break; case WifiManager.WIFI_STATE_DISABLING: break; } } // 监听网络连接,包括wifi和移动数据的打开和关闭,以及连接上可用的连接都会接到监听 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) { //获取联网状态的NetworkInfo对象 NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO); if (info != null) { //如果当前的网络连接成功并且网络连接可用 if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) { if (info.getType() == ConnectivityManager.TYPE_WIFI || info.getType() == ConnectivityManager.TYPE_MOBILE) { Log.i("TAG", getConnectionType(info.getType()) + "连上"); Toast.makeText(context, getConnectionType(info.getType()) + "连上", Toast.LENGTH_SHORT).show(); } } else { Log.i("TAG", getConnectionType(info.getType()) + "断开"); Toast.makeText(context, getConnectionType(info.getType()) + "断开", Toast.LENGTH_SHORT).show(); } } } }}
(2)基类 BasicActivity
/** * Activity基类:实时获取网络状态 * create by Travis1022 on 2017-10-11 */public class BasicActivity extends AppCompatActivity { private boolean isRegistered = false; private NetWorkChangReceiver netWorkChangReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //注册网络状态监听广播 netWorkChangReceiver = new NetWorkChangReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); registerReceiver(netWorkChangReceiver, filter); isRegistered = true; } @Override protected void onDestroy() { super.onDestroy(); //解绑 if (isRegistered) { unregisterReceiver(netWorkChangReceiver); } }}
(3) 在AndroidManifest.xml中声明广播以及对应的网络权限