Android仅使用蜂窝(3G,4G,EDGE)数据来处理服务器请求

时间:2015-07-22 16:42:27

标签: android retrofit okhttp cellular-network

我有一个应用程序,我希望仅将蜂窝数据用于服务器请求。 我不需要完全禁用WI-FI

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

也许只为我的应用做一种方法。我注意到我正在使用okHttp客户端进行改造,如:

    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();

    }

2 个答案:

答案 0 :(得分:3)

检查应用是否已连接到wifi,然后按如下方式阻止请求发生:

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

答案 1 :(得分:0)

像@Edson Menegatti所说的那样,我们可以像他的回答一样实施smth,但是如果有很多工具可以让我们的生活复杂化。所以,我使用了一种firewall可以禁用特定应用的移动数据。我必须提到我之所以做出这个决定只是因为 我的应用是内部公司,所以我可以管理所有员工设备。

当然,我会检查每个请求的互联网连接和可用性:

 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;
}

不得不提及有关ping选项的新编码器:

    -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.

并使用此检查器:

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

对于那些忘记如何构建弹出对话框的人:

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();
    }