我有一个应用程序,我希望仅将蜂窝数据用于服务器请求。 我不需要完全禁用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();
}
答案 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)
当然,我会检查每个请求的互联网连接和可用性:
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();
}