美文网首页
Android 监听网络变化

Android 监听网络变化

作者: 笑叶林 | 来源:发表于2018-06-07 16:48 被阅读13次

    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);
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Android 监听网络变化

          本文链接:https://www.haomeiwen.com/subject/sowgsftx.html