gpt4 book ai didi

android-intent - 防止在关闭屏幕时重新创建 Android Activity

转载 作者:行者123 更新时间:2023-12-03 14:40:20 25 4
gpt4 key购买 nike

如何防止在关闭屏幕时重新创建 Activity ?

我做什么

  1. Start Bejewels and go to the jewelry screen.
  2. Press power button shortly. The screen is turned off, but the device is not.
  3. Press power button again.


我看到的

The same screen as before turning screen off.



对于我的应用程序(一个微不足道的应用程序,只是一个带有单个 WebView 的 Web 应用程序),场景如下:

我做什么

  1. Start my app. The activity onCreate() method loads an URL into the WebView.
  2. Press power button shortly. The screen is turned off, but the device is not.
  3. Press power button again.


我看到的

The WebView is reloading the page.



我所期望的

As in Bejewels case I want to see the same screen, that for my app is the page in its previous state: scripts are running, a form fields are filled etc.



调试表明,我错了(在上一个问题中)并且 onDestroy() 和 onCreate() 在屏幕刚刚打开时被一个接一个地调用。而且由于我仍然听到由脚本播放的音乐,因此当屏幕关闭时,看起来 Activity 和 WebView 确实存在,直到我再次按下电源按钮。

我试过了。
  • android:alwaysRetainTaskState="true"相同的行为。
  • 阅读有关意图(无济于事,我只是不明白,它们如何应用于我的情况)。
  • 使用 PhoneGap。它的行为不同:只是在按下电源按钮时杀死整个应用程序。这更好,但不是最好的。
  • 最佳答案

    此问题的解决方案可能与此处描述的相同:onDestroy gets called each time the screen goes on

    由于配置更改,您的 Activity 似乎正在重新启动,请参阅 http://developer.android.com/guide/topics/resources/runtime-changes.html .最常见的是当您的应用程序处于横向模式(如大多数游戏一样)时,然后通过点击电源按钮启用屏幕锁定。屏幕锁定处于纵向模式,因此会触发方向更改,从而触发重新启动 Activity 。

    可以通过添加以下内容来覆盖此行为:

    android:configChanges="orientation|keyboardHidden"

    ... 如果您的目标 API 级别低于 13,则添加到您的 list 文件中。或者
    android:configChanges="orientation|keyboardHidden|screenSize"

    ...如果您的目标 API 级别大于 13。

    请注意,您可能需要转到 project->properties 并更新您的项目构建目标。如果您的构建目标小于 13,将无法识别“screenSize”。

    可能是导致 Activity 被重置的不同配置更改。以下链接提供了可能的配置更改列表: http://developer.android.com/guide/topics/manifest/activity-element.html#config

    关于android-intent - 防止在关闭屏幕时重新创建 Android Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10498636/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com