0

如何知道活動是否堆棧頂部?我想過使用onResume/onPause,但這並不完全一樣,因爲一旦應用程序轉到後臺,它會失敗。 事實是,我發送了一個接收到的所有活動的廣播接收器(我有一個由所有活動擴展並註冊到廣播的BaseActivity)。因此,只有位於堆棧頂部的活動必須對廣播作出反應。如果我使用isResumed(),它會一直工作,但是當應用程序轉到後臺時。任何想法?如何知道活動是否位於堆棧頂部

在此先感謝!

+1

http://stackoverflow.com/questions/3262157/how-to-check-if-my-activity-is-the-current-activity-running-in-the-screen – sasikumar

+0

感謝您回答,但這正是我所說的我正在做的。問題是這個解決方案並不完全正確,如果應用程序進入後臺,則不會恢復活動,因此沒有活動處理廣播接收器。 – FVod

回答

0
 in base activity you register the broadcast Receiver and in receiver function you call one abstract function which one is implemented by all child activities. 
     The activity which is on top will automatically receive that function call. 
     Edit sample code: 

     public abstract class BaseActivity extends AppCompatActivity { 
      private static final String NOTIFICATION_ARRIVED = "arrived"; 
      public abstract void receivedFunction(Intent intent); 
      private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { 
       @Override 
       public void onReceive(Context context, Intent intent) { 
        displayToast(" received in Base"); 
        receivedFunction(intent); 
       } 
      }; 

      public void displayToast(String s) { 
       Toast.makeText(this,s,Toast.LENGTH_SHORT).show(); 
      } 

      @Override 
      public void onResume() { 
       super.onResume(); 
       registerReceiver(mMessageReceiver, new IntentFilter(BaseActivity.NOTIFICATION_ARRIVED)); 
      } 

      @Override 
      public void onPause() { 
       super.onPause(); 
       unregisterReceiver(mMessageReceiver); 
      } 
     } 

     public class MainActivity extends BaseActivity { 
     @Override 
      public void receivedFunction(Intent intent) { 
       displayToast(" received in child"); 
      } 
     // do whetever you want . if you ovveride onpause and onResume then call super as well 
     } 
    or any other child 

    public class MainActivity2 extends BaseActivity { 
     @Override 
      public void receivedFunction(Intent intent) { 
       displayToast(" received in child"); 
      } 
     // do whetever you want . if you ovveride onpause and onResume then call super as well 
     } 

// to broadcast 

Intent intent = new Intent(BaseActivity.NOTIFICATION_ARRIVED); 
     sendBroadcast(intent); 
+0

所有已創建的活動都會收到廣播接收器,因爲寄存器在onCreate上完成,並且在onDestroy上未註冊。但我需要檢測哪一個是頂級活動,所以只有這個人處理接收器。我正在通過使用onResume/onPause方法來解決這個問題,但正如我所說的,這並不完全正確,因爲當應用程序進入後臺時,沒有任何活動處理接收器。 – FVod

+0

註冊在baseActivity的oncreate中,並在baseActivity中註銷ondestroy或onpause。 等待我寄給你樣品的希望,將幫助你 –

+0

非常感謝你的例子,問題是,當應用程序進入後臺,活動暫停,所以廣播接收機從來沒有收到 – FVod

相關問題