Android-系统服务-ConnectivityManager

0 快速索引表

  • 权限汇总

https://developer.android.google.cn/reference/android/Manifest.permission

/frameworks/base/core/res/AndroidManifest.xml

1

  • 接口汇总

https://developer.android.google.cn/reference/android/net/ConnectivityManager

/packages/modules/Connectivity/framework/src/android/net/ConnectivityManager.java

/frameworks/base/core/java/android/net/ConnectivityManager.java 

android.net.ConnectivityManager.requestNetwork

android.net.ConnectivityManager.setMobileDataEnabled

android.net.ConnectivityManager.getMobileDataEnabled

  • adb命令

adb shell svc data enable 

adb shell svc data disable

  • developer

执行网络操作概览  |  Android 开发者  |  Android Developers


1 需求


2 权限


3 接口

android.net.ConnectivityManager.requestNetwork

4205      /**
4206       * Helper function to request a network with a particular legacy type.
4207       *
4208       * This API is only for use in internal system code that requests networks with legacy type and
4209       * relies on CONNECTIVITY_ACTION broadcasts instead of NetworkCallbacks. New caller should use
4210       * {@link #requestNetwork(NetworkRequest, NetworkCallback, Handler)} instead.
4211       *
4212       * @param request {@link NetworkRequest} describing this request.
4213       * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4214       *                  before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4215       *                  be a positive value (i.e. >0).
4216       * @param legacyType to specify the network type(#TYPE_*).
4217       * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4218       * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4219       *                        the callback must not be shared - it uniquely specifies this request.
4220       *
4221       * @hide
4222       */
4223      @SystemApi
4224      @RequiresPermission(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK)
4225      public void requestNetwork(@NonNull NetworkRequest request,
4226              int timeoutMs, int legacyType, @NonNull Handler handler,
4227              @NonNull NetworkCallback networkCallback) {
4228          if (legacyType == TYPE_NONE) {
4229              throw new IllegalArgumentException("TYPE_NONE is meaningless legacy type");
4230          }
4231          CallbackHandler cbHandler = new CallbackHandler(handler);
4232          NetworkCapabilities nc = request.networkCapabilities;
4233          sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, legacyType, cbHandler);
4234      }
4236      /**
4237       * Request a network to satisfy a set of {@link NetworkCapabilities}.
4238       *
4239       * <p>This method will attempt to find the best network that matches the passed
4240       * {@link NetworkRequest}, and to bring up one that does if none currently satisfies the
4241       * criteria. The platform will evaluate which network is the best at its own discretion.
4242       * Throughput, latency, cost per byte, policy, user preference and other considerations
4243       * may be factored in the decision of what is considered the best network.
4244       *
4245       * <p>As long as this request is outstanding, the platform will try to maintain the best network
4246       * matching this request, while always attempting to match the request to a better network if
4247       * possible. If a better match is found, the platform will switch this request to the now-best
4248       * network and inform the app of the newly best network by invoking
4249       * {@link NetworkCallback#onAvailable(Network)} on the provided callback. Note that the platform
4250       * will not try to maintain any other network than the best one currently matching the request:
4251       * a network not matching any network request may be disconnected at any time.
4252       *
4253       * <p>For example, an application could use this method to obtain a connected cellular network
4254       * even if the device currently has a data connection over Ethernet. This may cause the cellular
4255       * radio to consume additional power. Or, an application could inform the system that it wants
4256       * a network supporting sending MMSes and have the system let it know about the currently best
4257       * MMS-supporting network through the provided {@link NetworkCallback}.
4258       *
4259       * <p>The status of the request can be followed by listening to the various callbacks described
4260       * in {@link NetworkCallback}. The {@link Network} object passed to the callback methods can be
4261       * used to direct traffic to the network (although accessing some networks may be subject to
4262       * holding specific permissions). Callers will learn about the specific characteristics of the
4263       * network through
4264       * {@link NetworkCallback#onCapabilitiesChanged(Network, NetworkCapabilities)} and
4265       * {@link NetworkCallback#onLinkPropertiesChanged(Network, LinkProperties)}. The methods of the
4266       * provided {@link NetworkCallback} will only be invoked due to changes in the best network
4267       * matching the request at any given time; therefore when a better network matching the request
4268       * becomes available, the {@link NetworkCallback#onAvailable(Network)} method is called
4269       * with the new network after which no further updates are given about the previously-best
4270       * network, unless it becomes the best again at some later time. All callbacks are invoked
4271       * in order on the same thread, which by default is a thread created by the framework running
4272       * in the app.
4273       * {@see #requestNetwork(NetworkRequest, NetworkCallback, Handler)} to change where the
4274       * callbacks are invoked.
4275       *
4276       * <p>This{@link NetworkRequest} will live until released via
4277       * {@link #unregisterNetworkCallback(NetworkCallback)} or the calling application exits, at
4278       * which point the system may let go of the network at any time.
4279       *
4280       * <p>A version of this method which takes a timeout is
4281       * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)}, that an app can use to only
4282       * wait for a limited amount of time for the network to become unavailable.
4283       *
4284       * <p>It is presently unsupported to request a network with mutable
4285       * {@link NetworkCapabilities} such as
4286       * {@link NetworkCapabilities#NET_CAPABILITY_VALIDATED} or
4287       * {@link NetworkCapabilities#NET_CAPABILITY_CAPTIVE_PORTAL}
4288       * as these {@code NetworkCapabilities} represent states that a particular
4289       * network may never attain, and whether a network will attain these states
4290       * is unknown prior to bringing up the network so the framework does not
4291       * know how to go about satisfying a request with these capabilities.
4292       *
4293       * <p>This method requires the caller to hold either the
4294       * {@link android.Manifest.permission#CHANGE_NETWORK_STATE} permission
4295       * or the ability to modify system settings as determined by
4296       * {@link android.provider.Settings.System#canWrite}.</p>
4297       *
4298       * <p>To avoid performance issues due to apps leaking callbacks, the system will limit the
4299       * number of outstanding requests to 100 per app (identified by their UID), shared with
4300       * all variants of this method, of {@link #registerNetworkCallback} as well as
4301       * {@link ConnectivityDiagnosticsManager#registerConnectivityDiagnosticsCallback}.
4302       * Requesting a network with this method will count toward this limit. If this limit is
4303       * exceeded, an exception will be thrown. To avoid hitting this issue and to conserve resources,
4304       * make sure to unregister the callbacks with
4305       * {@link #unregisterNetworkCallback(NetworkCallback)}.
4306       *
4307       * @param request {@link NetworkRequest} describing this request.
4308       * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4309       *                        the callback must not be shared - it uniquely specifies this request.
4310       *                        The callback is invoked on the default internal Handler.
4311       * @throws IllegalArgumentException if {@code request} contains invalid network capabilities.
4312       * @throws SecurityException if missing the appropriate permissions.
4313       * @throws RuntimeException if the app already has too many callbacks registered.
4314       */
4315      public void requestNetwork(@NonNull NetworkRequest request,
4316              @NonNull NetworkCallback networkCallback) {
4317          requestNetwork(request, networkCallback, getDefaultHandler());
4318      }
4320      /**
4321       * Request a network to satisfy a set of {@link NetworkCapabilities}.
4322       *
4323       * This method behaves identically to {@link #requestNetwork(NetworkRequest, NetworkCallback)}
4324       * but runs all the callbacks on the passed Handler.
4325       *
4326       * <p>This method has the same permission requirements as
4327       * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4328       * and throws the same exceptions in the same conditions.
4329       *
4330       * @param request {@link NetworkRequest} describing this request.
4331       * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4332       *                        the callback must not be shared - it uniquely specifies this request.
4333       * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4334       */
4335      public void requestNetwork(@NonNull NetworkRequest request,
4336              @NonNull NetworkCallback networkCallback, @NonNull Handler handler) {
4337          CallbackHandler cbHandler = new CallbackHandler(handler);
4338          NetworkCapabilities nc = request.networkCapabilities;
4339          sendRequestForNetwork(nc, networkCallback, 0, REQUEST, TYPE_NONE, cbHandler);
4340      }
4342      /**
4343       * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
4344       * by a timeout.
4345       *
4346       * This function behaves identically to the non-timed-out version
4347       * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, but if a suitable network
4348       * is not found within the given time (in milliseconds) the
4349       * {@link NetworkCallback#onUnavailable()} callback is called. The request can still be
4350       * released normally by calling {@link #unregisterNetworkCallback(NetworkCallback)} but does
4351       * not have to be released if timed-out (it is automatically released). Unregistering a
4352       * request that timed out is not an error.
4353       *
4354       * <p>Do not use this method to poll for the existence of specific networks (e.g. with a small
4355       * timeout) - {@link #registerNetworkCallback(NetworkRequest, NetworkCallback)} is provided
4356       * for that purpose. Calling this method will attempt to bring up the requested network.
4357       *
4358       * <p>This method has the same permission requirements as
4359       * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4360       * and throws the same exceptions in the same conditions.
4361       *
4362       * @param request {@link NetworkRequest} describing this request.
4363       * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4364       *                        the callback must not be shared - it uniquely specifies this request.
4365       * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4366       *                  before {@link NetworkCallback#onUnavailable()} is called. The timeout must
4367       *                  be a positive value (i.e. >0).
4368       */
4369      public void requestNetwork(@NonNull NetworkRequest request,
4370              @NonNull NetworkCallback networkCallback, int timeoutMs) {
4371          checkTimeout(timeoutMs);
4372          NetworkCapabilities nc = request.networkCapabilities;
4373          sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE,
4374                  getDefaultHandler());
4375      }
4377      /**
4378       * Request a network to satisfy a set of {@link NetworkCapabilities}, limited
4379       * by a timeout.
4380       *
4381       * This method behaves identically to
4382       * {@link #requestNetwork(NetworkRequest, NetworkCallback, int)} but runs all the callbacks
4383       * on the passed Handler.
4384       *
4385       * <p>This method has the same permission requirements as
4386       * {@link #requestNetwork(NetworkRequest, NetworkCallback)}, is subject to the same limitations,
4387       * and throws the same exceptions in the same conditions.
4388       *
4389       * @param request {@link NetworkRequest} describing this request.
4390       * @param networkCallback The {@link NetworkCallback} to be utilized for this request. Note
4391       *                        the callback must not be shared - it uniquely specifies this request.
4392       * @param handler {@link Handler} to specify the thread upon which the callback will be invoked.
4393       * @param timeoutMs The time in milliseconds to attempt looking for a suitable network
4394       *                  before {@link NetworkCallback#onUnavailable} is called.
4395       */
4396      public void requestNetwork(@NonNull NetworkRequest request,
4397              @NonNull NetworkCallback networkCallback, @NonNull Handler handler, int timeoutMs) {
4398          checkTimeout(timeoutMs);
4399          CallbackHandler cbHandler = new CallbackHandler(handler);
4400          NetworkCapabilities nc = request.networkCapabilities;
4401          sendRequestForNetwork(nc, networkCallback, timeoutMs, REQUEST, TYPE_NONE, cbHandler);
4402      }

android.net.ConnectivityManager.setMobileDataEnabled

  • 从Android L及更高版本开始,setMobileDataEnabled方法不再可调用 

/frameworks/base/core/java/android/net/ConnectivityManager.java 

886    /**
887     * Sets the persisted value for enabling/disabling Mobile data.
888     *
889     * @param enabled Whether the user wants the mobile data connection used
890     *            or not.
891     * @hide
892     */
893    public void setMobileDataEnabled(boolean enabled) {
894        try {
895            mService.setMobileDataEnabled(enabled);
896        } catch (RemoteException e) {
897        }
898    }

android.net.ConnectivityManager.getMobileDataEnabled

2516      /**
2517       * @hide
2518       * @deprecated Talk to TelephonyManager directly
2519       */
2520      @Deprecated
2521      @UnsupportedAppUsage
2522      public boolean getMobileDataEnabled() {
2523          TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2524          if (tm != null) {
2525              int subId = SubscriptionManager.getDefaultDataSubscriptionId();
2526              Log.d("ConnectivityManager", "getMobileDataEnabled()+ subId=" + subId);
2527              boolean retVal = tm.createForSubscriptionId(subId).isDataEnabled();
2528              Log.d("ConnectivityManager", "getMobileDataEnabled()- subId=" + subId
2529                      + " retVal=" + retVal);
2530              return retVal;
2531          }
2532          Log.d("ConnectivityManager", "getMobileDataEnabled()- remote exception retVal=false");
2533          return false;
2534      }

参考资料:

https://developer.android.google.cn/reference/android/net/ConnectivityManager

/packages/modules/Connectivity/framework/src/android/net/ConnectivityManager.java


4 示例


5 adb shell svc data 命令

adb shell svc data enable 

adb shell svc data disable


6 appops


  •   参考资料(权限)

https://developer.android.google.cn/reference/android/Manifest.permission

/frameworks/base/core/res/AndroidManifest.xml

  •  参考资料(接口)

https://developer.android.google.cn/reference/android/net/ConnectivityManager

/packages/modules/Connectivity/framework/src/android/net/ConnectivityManager.java

  •  参考资料(指南)

执行网络操作概览  |  Android 开发者  |  Android Developers

  • 参考资料(其它)

Android获取网络状态 - 简书

获取当前网络状态 - 东功 - 博客园

Android 获取网络状态 - 曙光XK - 博客园

Android详细教程(基础篇):三十三、Android获取服务getSystemService详解

Android 5.0以上移动网络开关


1 需求:

需求1:查询网络是否连接;

需求2:查询数据业务是否连接;

需求3:查询Wi-Fi是否连接;

需求4:查询网络连接类型、网络子类型;

需求5:跳转到数据开关设置页面;

需求6:跳转到Wi-Fi开关设置页面;


接口:

ConnectivityManager  |  Android Developers

java.lang.Object
   ↳    android.net.ConnectivityManager

  • Constants
    • public static final int TYPE_BLUETOOTH
    • public static final int TYPE_ETHERNET
    • public static final int TYPE_MOBILE
    • public static final int TYPE_WIFI
    • public static final int TYPE_WIMAX
  • Public methods
    • public Network getActiveNetwork ()
    • public NetworkInfo getActiveNetworkInfo ()
    • public NetworkInfo[] getAllNetworkInfo ()
    • public Network[] getAllNetworks ()
    • public NetworkInfo getNetworkInfo (int networkType)
    • public NetworkInfo getNetworkInfo (Network network)

NetworkInfo  |  Android Developers

java.lang.Object
   ↳    android.net.NetworkInfo

  • Public methods
    • public String getExtraInfo ()
    • public NetworkInfo.State getState ()
    • public int getSubtype ()
    • public String getSubtypeName ()
    • public int getType ()
    • public String getTypeName ()
    • public boolean isAvailable ()
    • public boolean isConnected ()
    • public boolean isConnectedOrConnecting ()
    • public boolean isFailover ()
    • public boolean isRoaming ()

NetworkInfo.State  |  Android Developers

java.lang.Object
   ↳    java.lang.Enum<android.net.NetworkInfo.State>
        ↳    android.net.NetworkInfo.State

  • Enum values
    • public static final NetworkInfo.State CONNECTED
    • public static final NetworkInfo.State DISCONNECTED

TelephonyManager  |  Android Developers

java.lang.Object
   ↳    android.telephony.TelephonyManager

  • Constants
    • public static final int NETWORK_TYPE_CDMA
    • public static final int NETWORK_TYPE_EDGE
    • public static final int NETWORK_TYPE_GPRS
    • public static final int NETWORK_TYPE_UMTS
    • public static final int NETWORK_TYPE_HSDPA
    • public static final int NETWORK_TYPE_EVDO_0
    • public static final int NETWORK_TYPE_LTE

权限:

Manifest.permission  |  Android Developers

  • android.permission.ACCESS_NETWORK_STATE
  • android.permission.CHANGE_NETWORK_STATE

示例:

package com.learn_android.network_state;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * CONNECTIVITY_SERVICE系统服务
 * 功能1:
 * 功能2:
 * 功能3:
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";
    private static TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv = (TextView) findViewById(R.id.tv);

        Button btn_network_available = (Button) findViewById(R.id.btn_network_available);
        Button btn_mobile_available = (Button) findViewById(R.id.btn_mobile_available);
        Button btn_wifi_available = (Button) findViewById(R.id.btn_wifi_available);
        Button btn_network_type = (Button) findViewById(R.id.btn_network_type);
        Button btn_mobile_setting = (Button) findViewById(R.id.btn_mobile_setting);
        Button btn_wifi_setting = (Button) findViewById(R.id.btn_wifi_setting);

        btn_network_available.setOnClickListener(this);
        btn_mobile_available.setOnClickListener(this);
        btn_wifi_available.setOnClickListener(this);
        btn_network_type.setOnClickListener(this);
        btn_mobile_setting.setOnClickListener(this);
        btn_wifi_setting.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_network_available:
                onClickNetworkAvailable();
                break;
            case R.id.btn_mobile_available:
                onClickMobileAvailable();
                break;
            case R.id.btn_wifi_available:
                onClickWifiAvailable();
                break;
            case R.id.btn_network_type:
                onClickNetworkType();
                break;
            case R.id.btn_mobile_setting:
                onClickMobileSetting();
                break;
            case R.id.btn_wifi_setting:
                onClickWifiSetting();
                break;
            default:
                ;
        }
    }

    /**
     * 判断网络是否连接
     */
    private void onClickNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null) {
            Boolean b = networkInfo.isAvailable();
            // 把boolean值转化成字符串可以使用String.valueOf()
            tv.setText(String.valueOf(b));
        } else {
            tv.setText("网络无连接");
        }
    }

    /**
     * 判断数据业务是否连接
     */
    private void onClickMobileAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (networkInfo != null) {
            String state = networkInfo.getState().toString();
            tv.setText(state);
        } else {
            tv.setText("网络无连接");
        }
    }

    /**
     * 判断Wi-Fi是否连接
     */
    private void onClickWifiAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (networkInfo != null) {
            String state = networkInfo.getState().toString();
            tv.setText(String.valueOf(state));
        } else {
            tv.setText("网络无连接");
        }
    }

    /**
     * 判断网络连接状态
     */
    private void onClickNetworkType() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null) {
            // getTypeName:MOBILE、WIFI
            String type = networkInfo.getTypeName();
            // 如果是MOBILE,getExtraInfo:cmnet、cmwap
            String extraInfo = networkInfo.getExtraInfo();
            // 4G:NETWORK_TYPE_LTE
            // 3G:联通的3G为UMTS或HSDPA 电信的3G为EVDO
            // 2G:移动和联通的2G为GPRS或EGDE,电信的2G为CDMA
            String subType = networkInfo.getSubtypeName();
            tv.setText("type is:" + type + "\nextraInfo is:" + extraInfo + "\nsubType is:" + subType);
        } else {
            tv.setText("网络无连接");
        }
    }

    /**
     * 跳转到数据网络设置页面
     */
    private void onClickMobileSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_WIRELESS_SETTINGS);
        startActivity(intent);
    }

    /**
     * 跳转到数据网络设置页面
     */
    private void onClickWifiSetting() {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_WIFI_SETTINGS);
        startActivity(intent);
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值