0

我知道在火力地堡的onDataChange()爲讓說addListenerForSingleValueEventAndroid Main Ui thread運行。如果將火力地堡onDataChange()在這個例子中運行?

我想了解,如果我運行此代碼ExecutorService內會發生什麼:在Android的主UI線程

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()仍然運行? 而here's的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

監聽器回調總是在主/ UI線程上運行。這是用於添加監聽線程不影響回調線程。

Log.d(TAG, "onDataChange: Thread=" + Thread.currentThread().getName()); 
:您可以通過添加一個日誌聲明回調輸出線程名稱確認此