【问题标题】:on back pressed from browser erases all my variable value从浏览器按下后会删除我所有的变量值
【发布时间】:2013-01-05 14:21:29
【问题描述】:

我有 button.Onclicking 按钮它 cals->选择浏览器->在选择浏览器时它会加载我的 Url。 从浏览器返回时,我以前在本地设置的所有变量值都被清除。变量具有用它们初始化的值。 例如:

i=0。

内部方法我分配 i=10

现在调用浏览器 // 我使用此代码调用浏览器

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(strUrl));

intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

startActivity(Intent.createChooser(intent, "Choose browser"));

它会加载 URL //

现在回到活动中

变量(i)值变为0。

【问题讨论】:

    标签: android android-intent android-browser


    【解决方案1】:

    您需要更好地了解 Activity 的生命周期。当您离开并从 Activity 状态返回时不会自动持久化。

    Android 生命周期:http://developer.android.com/training/basics/activity-lifecycle/index.html

    当您返回 Activity 时,您应该使用 onSavedInstanceState 来恢复您的状态。这是(链接的)文档给出的代码示例:

    static final String STATE_SCORE = "playerScore";
    static final String STATE_LEVEL = "playerLevel";
    ...
    
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        // Save the user's current game state
        savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
        savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
    
        // Always call the superclass so it can save the view hierarchy state
        super.onSaveInstanceState(savedInstanceState);
    }
    

    【讨论】:

    • Booger:是的,它是一个更好的方法。实际上,我在一个带有活动组的选项卡内有一个类。从浏览器向后按下它涉及到起始级别活动。TabActivty->Act 1(dint call finish( ))->Activ 2(dint call finish())->browser.on 从浏览器向后按下它会转到 TabActivty。请帮我解决这个问题
    • 但是它在 4.0.3 上运行良好。它在 2.3.3 模拟器上运行良好,但在 os 2.3.5 的实际设备中创建这样的错误
    • 这是(并且一直是)在 Android 应用程序中保持状态的方式(因此自引入操作系统以来没有改变)。也许你应该从你现在遇到的问题开始一个新的问题(我认为这个问题已经得到了充分的回答)。
    【解决方案2】:

    将你的变量声明为静态的

    static int i = 0;
    

    这不会将 i 重置为零。后按

    【讨论】:

    • 肮脏的黑客。使用 onSaveState 更干净
    • 卡迪尔侯赛因:谢谢你的建议。我已经将所有变量声明为静态变量并尝试过。但它会像第一次打开活动一样打开活动..
    • 您必须在退出应用程序时将所有变量设置为默认值。
    • 但是它在 4.0.3 上运行良好。它在 2.3.3 模拟器上运行良好,但在 os 2.3.5 的实际设备中创建这样的错误
    猜你喜欢
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 2012-08-11
    相关资源
    最近更新 更多