如何验证用户是否具有网络访问权限并在没有网络访问权限时显示弹出警报 [英] How to verify if user has network access and show a pop-up alert when there isn't
问题描述
我的名字是 Pablo,我目前正在构建一个 Flutter 应用程序.因此,我的应用程序从 Firebase 存储中获取了一些图像和音频,显然,在没有互联网连接的情况下,该应用程序不会显示图像也不会播放音频.我希望应用程序在没有 WIFI 或数据时向用户弹出警报;我该怎么做?
My name is Pablo and I am currently building a Flutter app. So, my app gets some images and audios from Firebase Storage, and obviously, without the internet connection, the app doesn't display the images and doesn't play the audios. I want the app to pop-up an alert to the user when there is no WIFI nor Data; how can I do that?
谢谢:)
推荐答案
你可以简单地使用一个函数来检查你是否有网络连接,通过 ping Google 服务器:
You can simply use a function to check if you have network connection, by pinging Google servers:
/system/bin/ping -c 1 8.8.8.8
在安卓中,这个函数看起来像这样:
In Android, this function looks like this:
public boolean isNetworkAvailable() {
Runtime runtime = Runtime.getRuntime();
try {
Process process = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = process.waitFor();
return (exitValue == 0);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return false;
}
在 Firestore 中,默认情况下启用离线持久性.因此,您可以检查用户是从缓存还是从 Firebase 服务器读取数据.更优雅的方法是使用 isFromCache()
函数.这是安卓的代码:
In Firestore, offline persistence is enabled by default. So you can check if the user reads data from the cache or from Firebase servers. A more elegant way would be to use isFromCache()
function. This is the code for Android:
yourDocRef.addSnapshotListener(new DocumentListenOptions().includeMetadataChanges(), new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
Log.d("listener.isFromCache: " + documentSnapshot.getMetadata().isFromCache());
}
});
这篇关于如何验证用户是否具有网络访问权限并在没有网络访问权限时显示弹出警报的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!