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

1.监听Activity的生命周期

在Application的onCreate方法中监听Activity的生命周期
 registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

            }

            @Override
            public void onActivityStarted(Activity activity) {

            }

            @Override
            public void onActivityResumed(Activity activity) {
                MyActivityManager.getInstance().setCurrentActivity(activity);
            }

            @Override
            public void onActivityPaused(Activity activity) {

            }

            @Override
            public void onActivityStopped(Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(Activity activity) {

            }
        });


2.保存当前Activity的状态

package cn.uniwa.uniwa.util;

import android.app.Activity;

import java.lang.ref.WeakReference;

/**
 * Created by zhoujian on 2018/1/19.
 */

public class MyActivityManager {
    
    private static MyActivityManager sInstance = new MyActivityManager();
    
    private WeakReference sCurrentActivityWeakRef;


    private MyActivityManager() {

    }

    public static MyActivityManager getInstance() {
        return sInstance;
    }

    public Activity getCurrentActivity() {
        Activity currentActivity = null;
        if (sCurrentActivityWeakRef != null) {
            currentActivity = sCurrentActivityWeakRef.get();
        }
        return currentActivity;
    }

    public void setCurrentActivity(Activity activity) {
        sCurrentActivityWeakRef = new WeakReference(activity);
    }

}


3.使用场景

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




你可能感兴趣的:(Android小知识点)