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

后端 未结 2 393
夕颜
夕颜 2021-01-14 20:20

I have an app which connects to a hardware device Wi-Fi hotspot. It seems that Android forward requests over other networks (3G/4G for example) instead the hotspot, since my

相关标签:
2条回答
  • 2021-01-14 21:00

    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" />
    
    0 讨论(0)
  • 2021-01-14 21:03

    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.

    0 讨论(0)
提交回复
热议问题