Friday, 3 July 2015

android, get current Activity reference

\


Rubbish code first:   (This code only give your activity's name!!!!)


        ActivityManager am= (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
       List<RunningTaskInfo> runningTasks = am.getRunningTasks(1);
       RunningTaskInfo rti = runningTasks.get(0);
       ComponentName component = rti.topActivity;
       Log.i(tag, component.getClassName());



Solution:

Keep a reference in Application.

In all activities, you update it "onResume()"  (I don't think you have to clean the reference, really!!!)


@Overridepublic void onResume() {
    super.onResume();
    MyApplication.setCurrentActivity(this);
}


Then in "MyApplication":


public static Activity getCurrentActivity() {
    return currerntActivity;
}

public static void setCurrentActivity(Activity activity) {
    currerntActivity = activity;
}

Don't even try to clean the reference (by setCurrentActivity(Null)) in OnStop, because sometime your current activity will be stopped and then you can't get it.  (Especial when you want to show a dialog. )

clean the reference in onDestroy() is also not a good idea. Because it may too late.... because it is still referenced by MyApplication, so it will never be destroyed by the system!!!!!

However it is not an issue because it will be clean by next displayed activity.  Keeping the current displayed activity's reference is make sense.







This is not totally right, but worth to have a look:

http://stackoverflow.com/questions/11411395/how-to-get-current-foreground-activity-context-in-android







No comments:

Post a comment