Firebase onDataChange()在这个例子中运行在哪里?

时间:2017-04-02 06:47:12

标签: android multithreading firebase firebase-realtime-database executorservice

我知道Firebase中的onDataChange()让我说addListenerForSingleValueEvent正在Android Main Ui thread上运行。

我想了解如果我在ExecutorService

中运行此代码会发生什么
runInBackground(new Runnable() {
@Override
public void run() {
    ref.child("SOME_KEY")
            .addListenerForSingleValueEvent
                    (new ValueEventListener() {
                         @Override
                         public void onDataChange(final DataSnapshot dataSnapshot) {
                             //.. do some work on Ui Thread or not??
                         }

                         @Override
                         public void onCancelled(DatabaseError databaseError) {
                             notificationRunning = false;
                         }
                     }
                    );
}
});
}

onDataChange()是否仍然在Android的主Ui线程上运行? 这是ExecutorService跑步者

/**
 * Submits request to be executed in background.
 * Threads submitted will be executed synchronously.
 *
 * @param runnable
 */
private void runInBackground(final Runnable runnable) {
    mBackgroundExecutor.submit(new Runnable() {
        @Override
        public void run() {
            try {
                runnable.run();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

ExecutorService

mBackgroundExecutor = Executors
        .newSingleThreadExecutor(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable runnable) {
                Thread thread = new Thread(runnable,
                        "Background executor service for OneSignal");
                thread.setPriority(Thread.MIN_PRIORITY);
                thread.setDaemon(true);
                return thread;
            }
        });

1 个答案:

答案 0 :(得分:1)

侦听器回调始终在主/ UI线程上运行。用于添加侦听器的线程不会影响回调线程。您可以通过向回输输出线程名称的日志语句来确认:

Log.d(TAG, "onDataChange: Thread=" + Thread.currentThread().getName());