Android中获取当前正在显示的Activity

1.监听Activity的生命周期

在Application的onCreate方法中监听Activity的生命周期

      
      
      
      
  1. registerActivityLifecycleCallbacks( new ActivityLifecycleCallbacks() {
  2. @Override
  3. public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
  4. }
  5. @Override
  6. public void onActivityStarted(Activity activity) {
  7. }
  8. @Override
  9. public void onActivityResumed(Activity activity) {
  10. MyActivityManager.getInstance().setCurrentActivity(activity);
  11. }
  12. @Override
  13. public void onActivityPaused(Activity activity) {
  14. }
  15. @Override
  16. public void onActivityStopped(Activity activity) {
  17. }
  18. @Override
  19. public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
  20. }
  21. @Override
  22. public void onActivityDestroyed(Activity activity) {
  23. }
  24. });


2.保存当前Activity的状态


       
       
       
       
  1. package cn.uniwa.uniwa.util;
  2. import android.app.Activity;
  3. import java.lang.ref.WeakReference;
  4. /**
  5. * Created by zhoujian on 2018/1/19.
  6. */
  7. public class MyActivityManager {
  8. private static MyActivityManager sInstance = new MyActivityManager();
  9. private WeakReference sCurrentActivityWeakRef;
  10. private MyActivityManager() {
  11. }
  12. public static MyActivityManager getInstance() {
  13. return sInstance;
  14. }
  15. public Activity getCurrentActivity() {
  16. Activity currentActivity = null;
  17. if (sCurrentActivityWeakRef != null) {
  18. currentActivity = sCurrentActivityWeakRef.get();
  19. }
  20. return currentActivity;
  21. }
  22. public void setCurrentActivity(Activity activity) {
  23. sCurrentActivityWeakRef = new WeakReference(activity);
  24. }
  25. }


3.使用场景

在服务中实时弹出被挤掉的对话框,就需要获取当前的Activity




你可能感兴趣的:(android)