我有一个应用程序,我希望它仅将蜂窝数据用于服务器请求.
我不需要完全禁用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();
}
解决方法:
检查应用程序是否已连接到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();
}