Search code examples
androidandroid-orientationactivity-lifecycle

Android: Execute code when app is "activated", not on orientation change


in my application (minSdkVersion 17, but I am flexible concerning this), I have a single activity. It displays some kind of timetable. I want to let it show the current day and scroll to the correct time. This functionality is already working perfectly fine.

I want to do this everytime when the app is started, or everytime when the app becomes active again (e.g. after pressing the home button and just clicking the app icon again without killing the app inbetween).

But I do NOT want to do this, when the device is rotated.

For example, I have a method:

private void scrollToNow() {
    // do the calculation and scroll all views to the correct position
    // this is code I already have fully functional!
}

And I want to execute it every time the activity gets active again, but NOT on orientation change.

I tried a lot of combinations (in onStart, onResume, onCreate), but none of them did the trick. I tried to build a solution using the savedInstanceState but failed.

Anybody got some tips or useful links for me?

Thanks alot,

Oliver


Solution

  • Please, think twice before you decide to check configuration changes manually.

    If your application doesn't need to update resources during a specific configuration change and you have a performance limitation that requires you to avoid the activity restart, then you can declare that your activity handles the configuration change itself, which prevents the system from restarting your activity.

    Note: Handling the configuration change yourself can make it much more difficult to use alternative resources, because the system does not automatically apply them for you. This technique should be considered a last resort when you must avoid restarts due to a configuration change and is not recommended for most applications.

    Try to save some flag in onSaveInstanceState and in onCreate check if there is savedInstanceState, then save it as field for example. This will give you information about does activity is 'recreated' or not. Then in 'onResume' check is this flag set or not. If not, then you are not 'recreated' your activity, so you can invoke scrollToNow()