当前位置:   article > 正文

Android网络监听_android 网络监听

android 网络监听

1.通过注册BroadCastReceiver进行网络监听。

        1)  添加网络权限   

  1. <uses-permission android:name="android.permission.INTERNET"/>
  2. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

        2)定义BroadCastReceiver     

  1. public class NetworkReceiver extends BroadcastReceiver {
  2. @Override
  3. public void onReceive(Context context, Intent intent) {
  4. // 监听网络连接,包括wifi和移动数据的打开和关闭,以及连接上可用的连接都会接到监听
  5. // 特殊注意:如果if条件生效,那么证明当前是有连接wifi或移动网络的,如果有业务逻辑最好把esle场景酌情考虑进去!
  6. if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
  7. //获取联网状态的NetworkInfo对象
  8. NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
  9. if (info != null) {
  10. //如果当前的网络连接成功并且网络连接可用
  11. if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {
  12. Log.e("nyz", getConnectionType(info.getType()) + "已连接");
  13. switch (info.getType()) {
  14. case ConnectivityManager.TYPE_WIFI:
  15. Log.e("nyz", "wifi网络" + "已连接");
  16. break;
  17. case ConnectivityManager.TYPE_MOBILE:
  18. Log.e("nyz", "数据网络" + "已连接");
  19. break;
  20. }
  21. } else {
  22. Log.e("nyz", getConnectionType(info.getType()) + "已断开");
  23. }
  24. } else {
  25. Log.e("nyz", "无网络");
  26. }
  27. }
  28. }
  29. /**
  30. * 获取连接类型
  31. *
  32. * @param type
  33. * @return
  34. */
  35. private String getConnectionType(int type) {
  36. String connType = "";
  37. if (type == ConnectivityManager.TYPE_MOBILE) {
  38. connType = "3-4G网络数据";
  39. } else if (type == ConnectivityManager.TYPE_WIFI) {
  40. connType = "WIFI网络";
  41. }
  42. return connType;
  43. }
  44. }

    需要注意的一点是 NetworkInfo 的两个方法:info.isConnected(); info.isAvailable();

    info.isConnected(),不推荐使用 了,推荐的是通过NetWorkCallBack的方式。

    通过这个方法判断网络是否可用是 return mState == State.CONNECTED;

判断的状态,和上面的Receiver中判断的方法是一样的。

  1. /**
  2. * Indicates whether network connectivity exists and it is possible to establish
  3. * connections and pass data.
  4. * <p>Always call this before attempting to perform data transactions.
  5. * @return {@code true} if network connectivity exists, {@code false} otherwise.
  6. * @deprecated Apps should instead use the
  7. * {@link android.net.ConnectivityManager.NetworkCallback} API to
  8. * learn about connectivity changes. See
  9. * {@link ConnectivityManager#registerDefaultNetworkCallback} and
  10. * {@link ConnectivityManager#registerNetworkCallback}. These will
  11. * give a more accurate picture of the connectivity state of
  12. * the device and let apps react more easily and quickly to changes.
  13. */
  14. @Deprecated
  15. public boolean isConnected() {
  16. synchronized (this) {
  17. return mState == State.CONNECTED;
  18. }
  19. }

  info.isAvailable(),从AndroidL开始总是返回true,所以用这个方法,不能准确判断,网络是否可用

  1. /**
  2. *Since Android L, this always returns {@code true}, because the system only
  3. * returns info for available networks.
  4. */
  5. @Deprecated
  6. public boolean isAvailable() {
  7. synchronized (this) {
  8. return mIsAvailable;
  9. }
  10. }

3)Activity中注册Receiver,在oDestroy中取消注册。

  1. private void registerNetWorkReceiver() {
  2. //注册网络状态监听广播
  3. netWorkReceiver = new NetworkReceiver();
  4. IntentFilter filter = new IntentFilter();
  5. filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
  6. registerReceiver(netWorkReceiver, filter);
  7. }
  8. @Override
  9. protected void onDestroy() {
  10. super.onDestroy();
  11. if (netWorkReceiver != null) {
  12. unregisterReceiver(netWorkReceiver);
  13. }
  14. }

2.通过CallBack的方式监听网络:

    1)定义NetworkCallbackImpl类,继承ConnectivityManager.NetworkCallback

  1. class NetworkCallbackImpl extends ConnectivityManager.NetworkCallback {
  2. @Override
  3. public void onAvailable(@NonNull Network network) {
  4. Log.e("nyz", "网络已连接");
  5. }
  6. @Override
  7. public void onLost(@NonNull Network network) {
  8. super.onLost(network);
  9. Log.e("nyz", "网络已断开");
  10. }
  11. @Override
  12. public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
  13. super.onCapabilitiesChanged(network, networkCapabilities);
  14. if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
  15. if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
  16. Log.e("nyz", "wifi 网络");
  17. } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
  18. Log.e("nyz", "蜂窝网络");
  19. } else {
  20. Log.e("nyz", "其他网络");
  21. }
  22. }
  23. }

     2)注册CallBack:

  1. mConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  2. NetworkRequest request = new NetworkRequest.Builder().build();
  3. networkCallback = new NetworkCallbackImpl();
  4. mConnMgr.requestNetwork(request, networkCallback);

   3)反注册:

  1. @Override
  2. protected void onDestroy() {
  3. super.onDestroy();
  4. mConnMgr.unregisterNetworkCallback(networkCallback);
  5. }

3.其他判断网络是否可用的方法:

     

  1. @SuppressLint("MissingPermission")
  2. public static boolean isNetworkAvailable(Context context) {
  3. ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  4. if (connMgr == null) {
  5. return false;
  6. }
  7. NetworkInfo[] infos = connMgr.getAllNetworkInfo();
  8. if (infos != null) {
  9. for (NetworkInfo info : infos) {
  10. if (info.getState() == NetworkInfo.State.CONNECTED) {
  11. return true;
  12. }
  13. }
  14. }
  15. return false;
  16. }

     

  1. public static boolean isNetConnected(Context context) {
  2. if (context != null) {
  3. ConnectivityManager mConnectivityManager = (ConnectivityManager) context
  4. .getSystemService(Context.CONNECTIVITY_SERVICE);
  5. NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
  6. if (mNetworkInfo != null) {
  7. return mNetworkInfo.isConnected();
  8. }
  9. }
  10. return false;
  11. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/576685
推荐阅读
相关标签
  

闽ICP备14008679号