android 获取当前的activity
- 当我们在开发过程中需要Activity的实例的时候,很多时候都是将Activity当做参数传入,这样使得程序不那么的灵活。也有可能导致内存泄露。下面提供一种方案来解决。需要在android API 14以上才能使用。
Framework 提供的回调方法来获取当前的Activity
android在API 14在application引入一个方法,registerActivityLifecycleCallbacks方法用来监听所有的Activity的生命周期回调方法。
在Application 的onCreate方法中使用registerActivityLifecycleCallbacks(callback)注册你的CallBack,如下:
registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
public void onActivityStopped(Activity activity) {
}
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityCreated(Activity arg0, Bundle arg1) {
// TODO Auto-generated method stub
}
@Override
public void onActivityDestroyed(Activity arg0) {
// TODO Auto-generated method stub
}
@Override
public void onActivityPaused(Activity arg0) {
// TODO Auto-generated method stub
}
@Override
public void onActivityResumed(Activity arg0) {
// TODO Auto-generated method stub
Log.d("application","---- onActivityResumed: "+arg0.toString());
MyActivityManager.getInstance().setCurrentActivity(arg0);
}
@Override
public void onActivitySaveInstanceState(Activity arg0, Bundle arg1) {
// TODO Auto-generated method stub
}
});
那么MyActivityManager就是来管理和缓存当期的Activity的,但是要注意内存泄露的问题,如果使用强引用会导致Activity的实例没法被释放掉,所以需要使用弱引用来持有Activity实例。
public class MyActivityManager {
private static MyActivityManager instance = new MyActivityManager();
private WeakReference<Activity> activityWeakReference;
private MyActivityManager() {
}
public static MyActivityManager getInstance() {
return instance;
}
public Activity getCurrentActivity() {
Activity currentActivity = null;
if (activityWeakReference != null) {
currentActivity = activityWeakReference.get();
}
return currentActivity;
}
public void setCurrentActivity(Activity activity) {
activityWeakReference = new WeakReference<Activity>(activity);
}
}
第一次博客写轻喷~~~