我知道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;
}
});
答案 0 :(得分:1)
侦听器回调始终在主/ UI线程上运行。用于添加侦听器的线程不会影响回调线程。您可以通过向回输输出线程名称的日志语句来确认:
Log.d(TAG, "onDataChange: Thread=" + Thread.currentThread().getName());