手机连着wifi时优先用4G访问网络

参考文章
https://blog.csdn.net/qq_32120667/article/details/77834469
https://blog.csdn.net/u010019468/article/details/72886859

代码说明
权限申请 申请权限方式如下

 //    https://stackoverflow.com/questions/32083410/cant-get-write-settings-permission/32083622#32083622
    public void youDesirePermissionCode(Activity context) {
        Log.e("##########test", "-----youDesirePermissionCode------");

        boolean permission;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            permission = Settings.System.canWrite(context);
        } else {
            permission = ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_SETTINGS) == PackageManager.PERMISSION_GRANTED;
        }
        if (permission) {
            //do your code
            work_main();
        } else {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_WRITE_SETTINGS);
                intent.setData(Uri.parse("package:" + context.getPackageName()));
                context.startActivityForResult(intent, MainActivity.CODE_WRITE_SETTINGS_PERMISSION);
            } else {
                ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.WRITE_SETTINGS}, MainActivity.CODE_WRITE_SETTINGS_PERMISSION);
            }
        }
    }

选择4G优先的代码

				NetworkRequest.Builder builder = new NetworkRequest.Builder();

                // 设置指定的网络传输类型(蜂窝传输) 等于手机网络
                builder.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR);

                // 设置感兴趣的网络功能
                builder.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);

                // 设置感兴趣的网络:计费网络
                // builder.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);

                NetworkRequest request = builder.build();
                ConnectivityManager.NetworkCallback callback = new ConnectivityManager.NetworkCallback() {


                    /**
                     * Called when the framework connects and has declared amx new network ready for use.
                     * This callback may be called more than once if the {@link Network} that is
                     * satisfying the request changes.
                     *
                     */
                    @TargetApi(Build.VERSION_CODES.M)
                    @Override
                    public void onAvailable(Network network) {
                        super.onAvailable(network);
                        Log.i("test", "已根据功能和传输类型找到合适的网络");

                        // 可以通过下面代码将app接下来的请求都绑定到这个网络下请求
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            connectivityManager.bindProcessToNetwork(network);
                        } else {
                            // 23后这个方法舍弃了
                            ConnectivityManager.setProcessDefaultNetwork(network);
                        }

                        // 也可以在将来某个时间取消这个绑定网络的设置
                        // if (Build.VERSION.SDK_INT >= 23) {
                        //      onnectivityManager.bindProcessToNetwork(null);
                        //} else {
                        //     ConnectivityManager.setProcessDefaultNetwork(null);
                        //}

                        UiHandler.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Log.e("##########test", "----loadUrl----");
                                    webView.loadUrl("https://m.baidu.com/from=1019023c/s?word=ip&ts=5299444&t_kt=0&ie=utf-8&fm_kl=5b36a6c8a7&rsv_iqid=0487751263&rsv_t=3a5cqEKIiwgQkhwUieQ2%252FLzJXKWceNBHmA78%252FYd6XdGu8nFD3WRIEUtWAqHdbW8&sa=ib&rsv_pq=0487751263&rsv_sug4=2833&ss=110000000001&inputT=875&tj=1");
                                    addContentView(webView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        });


                        //                    connectivityManager.unregisterNetworkCallback(this);
                        // 只要一找到符合条件的网络就注销本callback
                        // 你也可以自己进行定义注销的条件
                    }


                    public void onUnavailable() {
                        super.onUnavailable();
                        Log.e("##########test", "onUnavailable");
                    }

                    public void onLost(Network network) {
                        Log.e("##########test", "onLost");
                    }
                };
                connectivityManager.requestNetwork(request, callback);
            }

测试方法

4G下 chrome 百度ip是 223.111.66.89
4g+wifi    chrome 百度ip是 119.137.52.187
4g+wifi   app显示ip是 223.111.66.89
只连4g   app显示ip是 223.111.66.89
只连wifi    app显示没有找到4g网络 

代码分享
完整的代码下载点击这里 https://download.csdn.net/download/codehxy/11465126

如何判断移动网络是否可以用
5.0以下

public static boolean isMobileEnableReflex(Context context) {
    try {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        Method getMobileDataEnabledMethod = ConnectivityManager.class.getDeclaredMethod("getMobileDataEnabled");
        getMobileDataEnabledMethod.setAccessible(true);
        return (Boolean) getMobileDataEnabledMethod.invoke(connectivityManager);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

5.0以上

public boolean getMobileDataState()
{
    try
    {
        TelephonyManager telephonyService = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);

        Method getMobileDataEnabledMethod = telephonyService.getClass().getDeclaredMethod("getDataEnabled");

        if (null != getMobileDataEnabledMethod)
        {
            boolean mobileDataEnabled = (Boolean) getMobileDataEnabledMethod.invoke(telephonyService);

            return mobileDataEnabled;
        }
    }
    catch (Exception ex)
    {
        Log.e(TAG, "Error getting mobile data state", ex);
    }

    return false;
}

你可能感兴趣的:(Android,网络)