Firebase在哪里可以调用addChildEventListener以便节省带宽? [英] Firebase where to call addChildEventListener so that I can save bandwidth?

查看:60
本文介绍了Firebase在哪里可以调用addChildEventListener以便节省带宽?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用我的测试android应用程序,我试图计算如果我的用户每10秒或1分钟添加一个孩子并与5台设备同步,它将占用多少带宽.

With my test android app I am trying to calculate how much bandwidth it will take if my user add a child every 10sec or 1min and synced with 5 devices.

我的应用程序用户将每分钟创建一次数据,因此我必须计算每个用户每月的订阅费用.每个用户每月消耗的大概带宽.

My app users will create data every minute, so I have to calculate subscription cost for each user per month. Approximate bandwidth consumed by each user per month.

我要在MainActivity中调用addChildEventListener,并每隔10秒从BroadcastReceiver类中添加一个子级.

I am calling addChildEventListener in my MainActivity and adding child from a BroadcastReceiver class every 10sec.

  • 每次我重新启动应用程序时,它都会下载所有行,这意味着要占用带宽.

  • Everytime I restart the app it's downloading all the rows, which means consuming bandwidth.

如何减少带宽使用率,并使应用程序每次重新启动应用程序时仅检索新添加的子代?

How can I reduce the bandwidth usage and make app to retrieve only newly added child every time I restart the app?

如果我添加Firebase.getDefaultConfig().setPersistenceEnabled(true);并且用户在线仍然addChildEventListener正在下载所有数据,是从服务器下载还是从本地同步的数据下载?

If I add Firebase.getDefaultConfig().setPersistenceEnabled(true); and user is online still addChildEventListener downloading all data, it's downloaded from server or locally synced data?

这就是我正在尝试的.

MainActivity.java

public class MainActivity extends AppCompatActivity {

Button start, stop;
TextView status;
String url = "https://<my-app>.firebaseio.com/data";
Firebase mFirebaseRef;
AlarmManager alarmManager;
PendingIntent pendingIntent;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Firebase.setAndroidContext(this);
    mFirebaseRef.getDefaultConfig().setPersistenceEnabled(true);
    alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    start = (Button) findViewById(R.id.Start);
    stop = (Button) findViewById(R.id.stop);
    status = (TextView) findViewById(R.id.serviceText);
    mFirebaseRef = new Firebase(url);



    mFirebaseRef.addChildEventListener(new ChildEventListener() {
        @Override
        public void onChildAdded(DataSnapshot dataSnapshot, String s) {
            Log.d("Data onChildAdded", dataSnapshot.getValue().toString());
            //Toast.makeText(getBaseContext(), "data=" + dataSnapshot.getValue(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onChildChanged(DataSnapshot dataSnapshot, String s) {
            Log.d("Data onChildChanged", dataSnapshot.getValue().toString());
            //Toast.makeText(getBaseContext(), "data=" + dataSnapshot.getValue(), Toast.LENGTH_LONG).show();
        }

        @Override
        public void onChildRemoved(DataSnapshot dataSnapshot) {
            Log.d("Data onChildRemoved", dataSnapshot.getValue().toString());
            //Toast.makeText(getBaseContext(), "data=" + dataSnapshot.getValue(), Toast.LENGTH_LONG).show();

        }

        @Override
        public void onChildMoved(DataSnapshot dataSnapshot, String s) {
            Log.d("Data onChildMoved", dataSnapshot.getValue().toString());
            //Toast.makeText(getBaseContext(), "data=" + dataSnapshot.getValue(), Toast.LENGTH_LONG).show();

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {


        }
    });

    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            status.setText("Started..");
            Intent myIntent = new Intent(getApplicationContext(), MyServiceReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, myIntent, 0);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),10000,
                    pendingIntent);
        }
    });

    stop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            status.setText("Stopped");
            AlarmManager alarmManager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(getApplicationContext(), MyServiceReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
            alarmManager.cancel(pendingIntent);
        }
    });
}

@Override
protected void onStop() {
    super.onStop();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

BroadcastReceiver.java

 public class MyServiceReceiver extends BroadcastReceiver {

Firebase mFirebaseRef;
Firebase mFirebaseRef2;
String url = "https://<my-app>.firebaseio.com/data";
Context context=null;
String data = "With Firebase queries, we can selectively retrieve data based on various factors. To construct a query, you start by specifying how you want your data to be ordered using one of the ordering functions: orderByChild(), orderByKey(), orderByValue(), or orderByPriority()";

@Override
public void onReceive(final Context context, Intent intent) {
    this.context = context;
    Firebase.setAndroidContext(context);
    mFirebaseRef = new Firebase(url);
    Firebase ref = mFirebaseRef.child(System.currentTimeMillis()+"");
    ref.setValue(new RecordingModel("Meeting","https://www.stadd.com",data));
    Log.d("caught", "data saved");

}
}

推荐答案

每次重新启动应用程序时,如何...仅检索新添加的孩子?

您可以使用 Firebase查询限制侦听器下载的数据.因此,您不必将您的 ChildEventListener 直接附加到Firebase位置,而是将收到的最后一个孩子的密钥存储在某个地方(例如,SharedPreferences),然后仅从下一个孩子开始加载.

How can I ... retrieve only newly added child every time I restart the app?

You can use Firebase Queries to limit the data that is downloaded by a listener. So instead of attaching your ChildEventListener directly to a Firebase location, you store the key of the last child you've received somewhere (e.g. SharedPreferences) and then load only from that child onwards next time.

这是监视最后一项按键的快速方法:

This is a quick way to monitor the key of the last item:

String lastChildKey;
mFirebaseRef.orderByKey().limitToLast(1).addChildEventListener(new ChildEventListener() { 
    public void onChildAdded(DataSnapshot snapshot, String s) {
        lastChildKey = snapshot.getKey();
    }
})

有了这些知识,您可以从应用程序重新启动时最后看到的项目开始:

With that knowledge, you can start at the item you last saw when the app restarts:

Query newItems = mFirebaseRef.orderByKey().startAt(lastChildKey);
newItems.addChildEventListener(...

使用这种方法,您将必须管理自己的客户端状态,因为您实际上是在用自己的替代Firebase的客户端缓存/同步策略.

With this approach you will have to manage your own client-side state, since you're essentially replacing Firebase's client-side caching/synchronization strategy with your own.

这篇关于Firebase在哪里可以调用addChildEventListener以便节省带宽?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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