获取栈顶Activity
2018-09-04 本文已影响11人
毛毛虫撤回一条消息
private void initGlobeActivity() {
/**
* 获取栈顶activity
*/
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
@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) {
}
});
}
public class MyActivityManager {
private static MyActivityManagersInstance =new MyActivityManager();
private WeakReferencesCurrentActivityWeakRef;
private MyActivityManager() {
}
public static MyActivityManagergetInstance() {
return sInstance;
}
public ActivitygetCurrentActivity() {
Activity currentActivity =null;
if (sCurrentActivityWeakRef !=null) {
currentActivity =sCurrentActivityWeakRef.get();
}
return currentActivity;
}
public void setCurrentActivity(Activity activity) {
sCurrentActivityWeakRef =new WeakReference(activity);
}
}
调用 MyActivityManager.getInstance().getCurrentActivity();