Android开发

android如何获取顶层栈顶的activity

2018-10-29  本文已影响44人  古都旧城

为什么要获取栈顶的activity

等等类似上面的需求,都需要我们获取栈顶的activity。

怎么获取

方式1

一般我们都写有基类,可以在基类里面打印或者获取context,依赖于基类,某些不继承基类的就不能获取了。

public class BaseActivity extends Activity {
       
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("BaseActivity", getClass().getSimpleName());
    }
   
}

效果


image.png

方式2

通过在application里面使用registerActivityLifecycleCallbacks方法注册监听,可适用性更强,不必依赖于基类。

public class App extends Application {
    ActivityLifecycleCallbacks callbacks;
    @Override
    public void onCreate() {
        super.onCreate();
       if (BuildConfig.PRODUCT_MODE) {//屏蔽不必要的注册
             return;
        }
        //注册对app内所有activity 的生命周期监听
        registerActivityLifecycleCallbacks(callbacks = new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                Log.e("Test","onActivityCreated:"+activity.getLocalClassName());
            }

            @Override
            public void onActivityStarted(Activity activity) {
                Log.e("Test","onActivityStarted:"+activity.getLocalClassName());
            }

            @Override
            public void onActivityResumed(Activity activity) {
                Log.e("Test","onActivityResumed:"+activity.getLocalClassName());
            }

            @Override
            public void onActivityPaused(Activity activity) {
                Log.e("Test","onActivityPaused:"+activity.getLocalClassName());
            }

            @Override
            public void onActivityStopped(Activity activity) {
                Log.e("Test","onActivityStopped:"+activity.getLocalClassName());
            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                Log.e("Test","onActivitySaveInstanceState:"+activity.getLocalClassName());
            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                Log.e("Test","onActivityDestroyed:"+activity.getLocalClassName());
            }
        });
// 注销app内所有activity的生命周期监听
// unregisterActivityLifecycleCallbacks(callbacks);
    }

}

上一篇 下一篇

猜你喜欢

热点阅读