简体   繁体   中英

Java Android internet Access: WIFI or 3G

In my android application it has to access a remote server to send a request and to receive the response to continue the functionality.

I need to clarify that before send the request, do I have to specially select that it should be WIFI or Mobile(3G) Internet in a situation where both available. I am not sure that ANDROID OS itself will select the best among them Or will give an exception in runtime. I can't test it as I am working with emulator. Would like to know the standard way.

I can check whether it has connected with WIFI or 3G(Mobile) by the following code. Like to know before I send the request if I have to select that it should be WIFI or MOBILE(3G) internet. A proper guidance is highly appreciated. Thanks in advance...

   ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
   NetworkInfo[] netInfo = cm.getAllNetworkInfo();

   for (NetworkInfo ni : netInfo) 
   {
       if (ni.getTypeName().equalsIgnoreCase("WIFI") && ni.isConnected())
       {
            Toast.makeText(getApplicationContext(), "Connected to Internet with WIFI", Toast.LENGTH_LONG).show();
       }
       if (ni.getTypeName().equalsIgnoreCase("MOBILE") && ni.isConnected())
       {
            Toast.makeText(getApplicationContext(), "Connected to Internet with 3G", Toast.LENGTH_LONG).show();
       }
   }

do I have to specially select that it should be WIFI or Mobile(3G) Internet in a situation where both available

The OS handles this. If there is a known and configured WiFi access point available, Android will use it.

More importantly, you can't "select" it yourself. You get what the OS gives you.


The OS handles this. If there is a known and configured WiFi access point available, Android will use it.

That is true. I just wanted to verify this by running your code, so I did this and the results are.

Steps:

  1. Ensure Wifi is on and connected.
  2. Ensure Mobile(3G) network is on.
  3. Execute your code above

Results: android chooses wifi instead of mobile(3g)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM