防止从离线回来后写入Firebase [Android] [英] Prevent write to Firebase after back from offline [Android]

查看:105
本文介绍了防止从离线回来后写入Firebase [Android]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到,Firebase有能力在离线时在本地存储数据,并在设备重新联机时执行写入。然而,我想禁用这个功能在我的应用程序中的一些写入,因为我想阻止用户垃圾邮件的数据库。谢谢。根据Frank的说法,我们没有办法控制写队列。因此,我决定编写一个实用程序来检查网络连接。只有在有连接时才会执行写操作。



NetworkUtil.java:

  public class NetworkUtil {

private context context;

public NetworkUtil(上下文上下文){
this.context = context;

$ b $ public boolean hasNetwork(){
ConnectivityManager mConnectivityManager =(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
if(info == null ||!info.isConnected())
return false;
else
返回true;
}

}

活动:

  / *检查网络* / 
NetworkUtil networkUtil = new NetworkUtil(getApplicationContext());
boolean hasNetwork = networkUtil.hasNetwork();
$ b $ if(hasNetwork)
/ *执行写入firebase * /


I understood that Firebase has the capability to store the data locally during offline, and perform write when the device is back online.

However I would like to disable this feature for some writes in my application, as I would like to prevent the users to spam the database. Thanks.

解决方案

According Frank, there is no way we can control the write queue. Thus, I decided to write a utility to check for network connection. The write will be only executed if there is a connection.

NetworkUtil.java:

public class NetworkUtil {

    private Context context;

    public NetworkUtil(Context context) {
        this.context = context;
    }

    public boolean hasNetwork() {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        final NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
        if (info == null || !info.isConnected())
            return false;
        else
            return true;
    }

}

And I added this lines to my activity:

/* Check for network */
NetworkUtil networkUtil = new NetworkUtil(getApplicationContext());
boolean hasNetwork = networkUtil.hasNetwork();

if (hasNetwork)
    /* perform write to firebase */

这篇关于防止从离线回来后写入Firebase [Android]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆