简体   繁体   中英

Android use only cellular(3G, 4G, EDGE) data for server requests

I have an app and I'd like it to use only cellular data for server requests. I don't need to disable WI-FI completely like:

  WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
  wifiManager.setWifiEnabled(false);

Maybe there is a way to do it only for my app . I note that I'm using retrofit with okHttp client, smth like:

    private static void setupRestClient() {

        OkHttpClient client = new OkHttpClient();
        client.setConnectTimeout(5, TimeUnit.SECONDS);
        client.setReadTimeout(5, TimeUnit.SECONDS);
        client.setRetryOnConnectionFailure(true);

        RestAdapter restAdapter = new RestAdapter.Builder()
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .setEndpoint(new EndpointManager())
                .setClient(new OkClient(client))
                .build();

    }

Check that the app is connected to wifi and then prevent the requests from happening as follows:

public static boolean isOnWifi(Context context) {
    ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    return mWifi.isConnected();
}

like @Edson Menegatti said, we can implement smth like his answer, but why should we complicate our life if there are a lot of tools for that. So, I used a kind of firewall who can disable cellular data for a certain app. I have to mention that I took this decision only because my app is internal company , so I can manage all employees devices.

Of course I have a kind of check for internet connection and availability for every request:

 public boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
    return networkInfo != null && networkInfo.isConnectedOrConnecting() && isOnline();
}

public boolean isOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c1 -w1 8.8.8.8");
        int exitValue = ipProcess.waitFor();
        return (exitValue == 0);

    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    return false;
}

Have to mention about ping option, for new coders:

    -c count

                  Stop  after  sending  count  ECHO_REQUEST packets. With deadline option, ping
                  waits for count ECHO_REPLY packets, until the timeout expires.


   -w deadline
                      Specify a timeout, in seconds, before ping exits regardless of how many pack‐
                      ets  have  been sent or received. In this case ping does not stop after count
                      packet are sent, it waits either for deadline expire or  until  count  probes
                      are answered or for some error notification from network.

And use this checker like:

//check connection
        if (isNetworkAvailable(context)) {
            doServerRequest();                
        } else {
            doConnectionAdvertisment(context);
        }

For those who forgot how to build a popup dialog:

public void doCheckConnectionAdvertisment(final Context context) {
        //alert dialog message
        new AlertDialog.Builder(context)
                .setTitle("Caution!")
                .setMessage("Please check your internet connection and try again")
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        //do something
                    }
                })
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setCancelable(false)
                .show();
    }

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