How to detect if a network is (configured as) a mobile hotspot on Android?

假如想象 提交于 2019-11-30 09:26:28

You can access this information by calling ConnectivityManager.isActiveNetworkMetered().

This will return whether the active connection is a hotspot (as defined in Data Usage -> Mobile Hotspots).

About the second part, I'm sorry but I don't think that's possible. The flag is not public, and even if you get the object that could be used to retrieve it (android.net.NetworkPolicyManager) by reflection:

Object npm = Class.forName("android.net.NetworkPolicyManager").getDeclaredMethod("from", Context.class).invoke(null, this);
Object policies = npm.getClass().getDeclaredMethod("getNetworkPolicies").invoke(npm);

calling getNetworkPolicies() requires the MANAGE_NETWORK_POLICY permission, which cannot be obtained by non-system apps, because it has a "signature" protection level.

I hope to be proved incorrect though. :) Maybe looking at the source code of the Android activity that manages this information (https://github.com/android/platform_packages_apps_settings/blob/master/src/com/android/settings/net/DataUsageMeteredSettings.java), in particular the buildWifiPref() method, will provide some clue.

I do not know if what you want is possible but you can check whether your device is connected to a network by checking the ip. You can use the tool below to see if you has ip, and shalt know if he is connected to a network or not.

public static Boolean check_connection(final Context _context)
  {
      boolean connected;

      ConnectivityManager conectivtyManager = (ConnectivityManager) _context
              .getSystemService(Context.CONNECTIVITY_SERVICE);

      if (conectivtyManager.getActiveNetworkInfo() != null
              && conectivtyManager.getActiveNetworkInfo().isAvailable()
              && conectivtyManager.getActiveNetworkInfo().isConnected())
      {
          connected = true;

      } else
      {
          connected = false;
      }
      return connected;
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!