在Application的onCreate方法中:
@Override
public void onCreate() {
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
().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) {
}
});
}
创建一个ActivityManager类
public class MyActivityManager {
private static MyActivityManager sInstance = new MyActivityManager();
private WeakReference<Activity> sCurrentActivityWeakRef;
private Object activityUpdateLock = new Object();
private MyActivityManager() {
}
public static MyActivityManager getInstance() {
return sInstance;
}
public Activity getCurrentActivity() {
Activity currentActivity = null;
synchronized (activityUpdateLock){
if (sCurrentActivityWeakRef != null) {
currentActivity = ();
}
}
return currentActivity;
}
public void setCurrentActivity(Activity activity) {
synchronized (activityUpdateLock){
sCurrentActivityWeakRef = new WeakReference<Activity>(activity);
}
}
}
在需要获取当前应用栈顶activity时
().getCurrentActivity();
这样就获取到当前栈顶的activity了