Use cellular data for internet when wifi and cellular data both are ON and wifi has no internet connectivity
Currently the use case is something like this, that we have to maintain Wifi P2P connection and when some callback is received using Wifi P2P connection then we have to push that to an API using cellular data without breaking Wifi P2P connection.
Wifi has no internet connectivity so it is compulsory to use Cellular data to push that received message to API.
I tried this by searching similar SO posts:
class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) forceConnectionToMobile2() button.setOnClickListener { Log.v("sahil", "${isConnected()}") } } fun forceConnectionToMobile2() { val connection_manager = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val request = NetworkRequest.Builder() Log.d("sahil", "request TRANSPORT_CELLULAR") request.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR) request.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) connection_manager.requestNetwork(request.build(), object : NetworkCallback() { override fun onAvailable(network: Network) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Log.d("sahil", "binding app to cellular network") connection_manager.bindProcessToNetwork(network) } } }) } } @Throws(InterruptedException::class, IOException::class) fun isConnected(): Boolean { val command = "ping -c 1 google.com" return Runtime.getRuntime().exec(command).waitFor() == 0 } }
When I connect my device to wifi using hotspot from other device which has no internet connectivity and turn on cellular data, I am getting "False" in "isConnected()".
What should I do to forcefully use Cellular data even when device is connected to Wifi?