如何知道活动是否在堆栈顶部

时间:2016-02-26 11:50:37

标签: android android-activity android-lifecycle android-broadcast android-broadcastreceiver

我怎么知道活动是否是堆栈的顶部?我想过使用onResume / onPause,但这并不完全正确,因为一旦应用程序进入后台,它就会失败。 事实是我正在发送一个接收所有活动的广播接收器(我有一个BaseActivity,由所有活动扩展并注册到广播)。因此,只有位于堆栈顶部的活动必须对广播做出反应。如果我使用isResumed()然后它会一直工作但是当应用程序转到后台时。有什么想法吗?

提前致谢!

1 个答案:

答案 0 :(得分: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);