Firebase Android:onDataChange() 事件总是在主 UI 线程中执行? [英] Firebase Android: onDataChange() event always executed in Main UI Thread?

查看:27
本文介绍了Firebase Android:onDataChange() 事件总是在主 UI 线程中执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 Firebase 的 Android 应用程序中,一旦 Firebase 返回查询答案,我需要在后台执行长操作.例如:

query.addListenerForSingleValueEvent(new ValueEventListener() {@覆盖公共无效 onDataChange(数据快照数据){做某事很长...然后为UI线程调用回调}

我知道 firebase 以异步模式执行查询,但 onDataChange() 方法似乎总是在主 UI 线程中执行,即使我尝试在自定义后台线程中调用查询.

有人知道如何管理这个用例吗?

解决方案

Firebase 侦听器的回调确实在主 UI 线程上执行.

如果您需要在回调中执行繁重的操作,请启动一个AsyncTask 并在那里完成工作.AsyncTask.doInBackground() 方法在不同的线程上执行,因此它不会阻塞 Android UI.但是AsyncTask.onPostExecute() 再次在主线程上执行,因此您可以从那里更新您的 UI 视图.

如果您使用 Cloud Firestore,请参阅Abhriya Roy 的回答,了解如何在后台线程上获取回调.>

In an Android application using Firebase, I need to execute long operations in background once Firebase returns a query answer. E.g.:

query.addListenerForSingleValueEvent(new ValueEventListener() {
   @Override
   public void onDataChange(DataSnapshot data) {
         dosomething very long. . .
         then call a callback forUI thread
   }

I know that firebase execute the query in asynchronous mode but the onDataChange() method seems to be always executed in the main UI Thread, even if I try to call the query in a custom background Thread.

Does anyone knows how to manage this use case?

解决方案

The callbacks for your Firebase listeners are indeed executed on the main UI thread.

If you need to do heavy operations in a callback, spin up an AsyncTask and do the work there. The AsyncTask.doInBackground() method executes on a different thread, so it won't block the Android UI. But AsyncTask. onPostExecute() executes on the main thread again, so you can update your UI views from there.

If you're using Cloud Firestore, see Abhriya Roy's answer on how to get the callbacks on a background thread.

这篇关于Firebase Android:onDataChange() 事件总是在主 UI 线程中执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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