且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-15 17:25:20

你可以简单地使用一个函数来检查你是否有网络连接,通过 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());
    }
});