Android开发中需要用到当前 activity实例,如何获取当前正在显示的Activity实例
1.保存当前Activity实例
import android.app.Activity;
import java.lang.ref.WeakReference;
public class MyActivityManager {
private static MyActivityManager sInstance = new MyActivityManager();
private WeakReference<Activity> sCurrentActivityWeakRef;
private MyActivityManager() {
}
public static MyActivityManager getInstance() {
return sInstance;
}
public Activity getCurrentActivity() {
Activity currentActivity = null;
if (sCurrentActivityWeakRef != null && sCurrentActivityWeakRef.get() != null) {
currentActivity = sCurrentActivityWeakRef.get();
}
return currentActivity;
}
public void setCurrentActivity(Activity activity) {
sCurrentActivityWeakRef = new WeakReference<Activity>(activity);
}
}
2.监听Activity的生命周期
在Application的onCreate方法中监听Activity的生命周期
private void initLifeCycle() {
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
MyActivityManager.getInstance().setCurrentActivity(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) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
});
}
3.使用
activity = MyActivityManager.getInstance().getCurrentActivity();
注意:很多人在onResume方法中对当前实例对象进行赋值,原理上是对的,其实有隐患,储存当前activity的单例类,可能在任意一个地方被调用,比如在某个activity的oncreate方法里执行,这时候会发生取错,进而发生很多不知名bug,正确做法,应该是oncreate和onResume方法里都对单例类进行赋值,保证随时取到的都是最新的正确值。