简体   繁体   English

如何验证用户是否可以访问网络并在没有访问权限时显示弹出警报

[英]How to verify if user has network access and show a pop-up alert when there isn't

My name is Pablo and I am currently building a Flutter app. 我叫Pablo,目前正在开发Flutter应用。 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. 因此,我的应用程序从Firebase Storage获取了一些图像和音频,并且显然,如果没有Internet连接,该应用程序将不会显示图像,也不会播放音频。 I want the app to pop-up an alert to the user when there is no WIFI nor Data; 我希望该应用在没有WIFI或数据的情况下向用户弹出警报; how can I do that? 我怎样才能做到这一点?

Thanks :) 谢谢 :)

You can simply use a function to check if you have network connection, by pinging Google servers: 您可以通过ping Google服务器来简单地使用一个函数来检查您是否有网络连接:

/system/bin/ping -c 1 8.8.8.8

In Android, this function looks like this: 在Android中,此函数如下所示:

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;
}

In Firestore, offline persistence is enabled by default. 在Firestore中,默认情况下启用了离线持久性。 So you can check if the user reads data from the cache or from Firebase servers. 因此,您可以检查用户是否从缓存或Firebase服务器读取数据。 A more elegant way would be to use isFromCache() function. 一种更优雅的方法是使用isFromCache()函数。 This is the code for Android: 这是Android的代码:

yourDocRef.addSnapshotListener(new DocumentListenOptions().includeMetadataChanges(), new EventListener<DocumentSnapshot>() {
    @Override
    public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
        Log.d("listener.isFromCache: " + documentSnapshot.getMetadata().isFromCache());
    }
});

For showing alert part, you can use RFlutter Alert library. 对于显示警报部分,您可以使用RFlutter警报库。 It is easily customizable and easy-to-use alert/popup dialog library for Flutter. 它是Flutter的易于自定义且易于使用的警报/弹出对话框库。

Example code: 示例代码:

Alert(context: context, title: "RFLUTTER", desc: "Flutter is awesome.").show();

*I'm one of developer of RFlutter Alert. *我是RFlutter Alert的开发人员之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM