强制使用TRASPORT_CELLULAR网络

时间:2016-07-08 00:34:14

标签: android

我正在编写代码以强制使用移动网络,但当我尝试查看getActiveNetworkInfo时,它仍然可以连接到WIFI。

以下代码总是给我 - “MOBILE Network wifi !!”在NetworkCallback的onAvailable方法中。

/**
 * Attempt to force usage of cellular network on devices with API 21+ (i.e. LOLLIPOP)
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void useCellularNetworkApi21(final VZCAuthActivity.CellNetworkCallBack callback) {
    final NetworkRequest networkReq = new NetworkRequest.Builder()
            .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
            .addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
            .build();

    mConnectivityManager.requestNetwork(networkReq, new ConnectivityManager.NetworkCallback() {
        @Override
        public void onAvailable(Network network) {
            boolean b = false;
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                b = ConnectivityManager.setProcessDefaultNetwork(network);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                b = mConnectivityManager.bindProcessToNetwork(network);
            }


            NetworkInfo networkInfo=mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            NetworkInfo activeNetwork = mConnectivityManager.getActiveNetworkInfo();
            boolean isConnected = activeNetwork != null &&
                    activeNetwork.isConnectedOrConnecting();

            NetworkInfo wifi = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            NetworkInfo mobile = mConnectivityManager .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

            if (wifi.isConnected()){
                Log.d(VZCCommons.LOGTAG, "MOBILE Network wifi !!" );
            }

            if (mobile.isConnected()) {
                //if internet connected
                Log.d(VZCCommons.LOGTAG, "MOBILE Network mobile !!" );
            }


            if (BuildConfig.DEBUG) {
                Log.d(LOGTAG, "Device switched network to MOBILE Network:" + b);
                Log.d(LOGTAG, "Device switched network to MOBILE Network isConnected:" + isConnected);
                Log.d(LOGTAG, "MOBILE Network info:" + activeNetwork.getType());
            }
            callback.onCellNetworkComplete();
        }

    });

}

0 个答案:

没有答案