Android:当应用处于 "activated" 时执行代码,而不是方向改变时

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

在我的申请中(minSdkVersion 17,但我对此很灵活),我有一个 activity。它显示某种时间表。我想让它显示当前日期并滚动到正确的时间。 此功能已经运行良好。

我想在每次启动应用程序时执行此操作,或者每次应用程序再次激活时(例如,在按下主页按钮后再次单击应用程序图标而不会在其间终止应用程序)。

但我不想在设备旋转时执行此操作。

比如我有一个方法:

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

我想在每次 activity 再次激活时执行它,但不是在方向改变时执行。

我尝试了很多组合(在 onStartonResumeonCreate 中),但其中 none 成功了。我尝试使用 savedInstanceState 构建解决方案但失败了。

有人给我一些提示或有用的链接吗?

非常感谢,

奥利弗

I dont want to recreate layout when screen orientation change

您是否尝试过将此行添加到您的 AndroidManifest.xml android:configChanges="screenLayout|screenSize|orientation" 中:

<activity
        android:name="youractivity"
        android:configChanges="screenLayout|screenSize|orientation"
        android:label="@string/title_activity_create_note"
        android:theme="@style/AppTheme"
        android:windowSoftInputMode="stateAlwaysHidden" />

有关更多信息,您可以查看:manifest/activity-element 在该页面中转到 android:configChanges 部分并阅读。

添加这个时你必须自己处理 onConfigurationChanged() 方法而不是 Android 系统。

请仔细阅读该页面的注释部分:

Note: Using this attribute should be avoided and used only as a last resort. Please read Handling Runtime Changes for more information about how to properly handle a restart due to a configuration change.

我也在我的应用程序中使用它也许你也可以试试这个:android:screenOrientation="nosensor"在那个页面你也可以找到关于它的信息。

请在决定手动检查配置更改之前三思。

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.

尝试在onSaveInstanceState中保存一些标志,并在onCreate中检查是否有savedInstanceState,然后将其保存为例如字段。这将为您提供有关 activity 是否为 'recreated' 的信息。然后在 'onResume' 检查是否设置了这个标志。如果不是,那么你不是 'recreated' 你的 activity,所以你可以调用 scrollToNow()