我正在尝试为我的Android应用使用FirebaseAuth
来实现signInWithEmailAndPassword()
的登录身份验证。我如何处理Internet连接脱机的情况,以便生成关于网络问题的Toast message
。
答案 0 :(得分:0)
这就是我的方法,我创建了一个类...然后使用以下代码。
public class InternetStatus {
private static InternetStatus instance = new InternetStatus();
static Context context;
ConnectivityManager connectivityManager;
NetworkInfo wifiInfo, mobileInfo;
boolean connected = false;
public static InternetStatus getInstance(Context ctx) {
context = ctx.getApplicationContext();
return instance;
}
public boolean isOnline() {
try {
connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
connected = networkInfo != null && networkInfo.isAvailable() &&
networkInfo.isConnected();
return connected;
} catch (Exception e) {
System.out.println("CheckConnectivity Exception: " + e.getMessage());
Log.v("connectivity", e.toString());
}
return connected;
}
}
然后为了使用它...
if (InternetStatus.getInstance(getApplicationContext()).isOnline()) {
Log.i(TAG, "User is online");
// proceed with your firebase auth code.
} else {
Log.e(TAG, "User does not have an internet connection");
//create a toast message, or however you want to handle this error.
}
答案 1 :(得分:0)
经过一番摆弄之后,我发现可以使用OnFailureListener
来处理它,因为Exception
生成的signInWithEmailAndPassword()
是FirebaseNetworkException
的实例。
答案 2 :(得分:0)
您可以使用以下代码段:
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e(LOG_TAG, "Error checking internet connection", e);
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
,并将其添加到您的Manifest.xml中:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>