如何处理“没有互联网连接"?发送请求时发生什么情况? [英] How to handle "no internet connection" scenario when sending requests?
问题描述
我目前正在开发基于FCM(Firebase云消息)的即时消息应用程序.我的问题在于以下情况:
I'm currently developing an instant message application based on FCM (Firebase Cloud Message). My problem lies in the follow scenario:
- 用户已连接到间歇性网络-即虽然与设备保持连接但仍可能会不时失去与互联网提供商的互联网连接的wi-fi;
- 当设备连接到wi-fi但没有互联网连接时,用户尝试发送消息(使用排球的POST请求);
解决此问题的最佳方法是什么?到目前为止,我已经使用BroadcastReceiver实现了一个用于网络更改的侦听器,但是,一旦wi-fi连接没有丢失,仅处理上述情况是不够的.
What is the best way to tackle this issue? So far, I've implemented a listener for network change using BroadcastReceiver, however, it is not enough to deal with the scenario described above once the wi-fi connection is not lost.
推荐答案
我为此创建了自己的实用程序类.每当我想进行网络呼叫时,无论成功还是失败,我都会使用回调.正在使用的库为 MaterialDialog
I created my own utility class for that. Whenever I want to make a network call I use the callbacks whenever its a success or a failure. The Library in use is MaterialDialog
public class NetworkUtil {
public static boolean isOnline() {
InetAddress inetAddress = null;
try {
Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() {
@Override
public InetAddress call() {
try {
return InetAddress.getByName("google.com");
} catch (UnknownHostException e) {
return null;
}
}
});
inetAddress = future.get(2000, TimeUnit.MILLISECONDS);
future.cancel(true);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
return inetAddress != null && !inetAddress.equals("");
}
public static MaterialDialog checkConnectivity(final Activity activity, final NetworkUtilCallback callback) {
MaterialDialog dialog = MaterialDialogUtil.builDialogPositiveNegative(activity,
activity.getString(R.string.no_internet),
activity.getString(R.string.instruction_no_internet),
"RETRY",
"CANCEL",
new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog dialog, DialogAction which) {
dialog.dismiss();
if (!isOnline()) {
checkConnectivity(activity, callback);
} else {
callback.onSuccess();
}
}
},
new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog dialog, DialogAction which) {
dialog.dismiss();
callback.onCancel();
}
});
if (!isOnline()) {
dialog.show();
} else {
callback.onSuccess();
}
return dialog;
}
public interface NetworkUtilCallback {
void onSuccess();
void onCancel();
}
这篇关于如何处理“没有互联网连接"?发送请求时发生什么情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!