Android - force network requests go through wifi instead of mobile network

会有一股神秘感。 提交于 2019-12-02 00:31:36

Per the Connecting your App to a Wi-Fi Device blog post:

To direct all the network requests from your app to an external Wi-Fi device, call ConnectivityManager#setProcessDefaultNetwork on Lollipop devices, and on Marshmallow call ConnectivityManager#bindProcessToNetwork instead, which is a direct API replacement.

Use the ConnectivityManager to get the state of the Wifi adapter and then you can check if it is connected or even available using NetworkInfo.

ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

if (wifi.isConnected()) {
    // Continue with logic
}

In case he is not connected to wifi then don't proceed else continue you flow.

Add the following permission in you Manifest file

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!