【问题标题】:How to prevent or handle onResume being called when phone screen is locked?如何防止或处理手机屏幕锁定时调用onResume?
【发布时间】:2017-12-28 10:49:29
【问题描述】:

默认情况下,我的应用设置为横向方向。当设备被锁定时,这会导致问题,因为方向将更改为纵向(以适应锁定的屏幕),这反过来又会强制调用 onResume。发生这种情况时,所有对象都为空,从而使应用程序容易崩溃。我进行了更改以防止崩溃,并且该应用程序运行正常。好的,这意味着当您从锁定屏幕返回应用程序时,用户界面会在半秒内处于纵向,然后再捕捉到正确的方向。

我已经解决的问题

我。对所有在 onResume 中永远不会为空的对象添加了空检查

二。在清单中添加android:configChanges="orientation|screenSize"

三。在清单中添加android:screenOrientation="landscape"

还有什么可以让我的应用程序从锁定屏幕转换回更顺畅,不会出现闪烁、闪烁或方向变化?

【问题讨论】:

    标签: android screen-orientation device-orientation


    【解决方案1】:

    从你的问题中我可以理解。您面临onResume() 中所有对象的空值,这会导致应用程序崩溃。 而且您无法真正避免再次调用onResume()。这是活动生命周期中的预期行为。但有一个窍门。您可以创建一个标志来了解onPause() 中的屏幕是否关闭/打开。手机解锁后,它会调用onResume(),您可以管理该标志。

    boolean isScreenUnLock = false;        
    @Override
    protected void onPause() {
         super.onPause();
         PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
         isScreenUnLock = pm.isScreenOn();      
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        if(isScreenUnLock){
            //Do something
        }
    }
    

    但这似乎不是更好的方法。我建议处理活动状态,而不是避免 Activity null 中的所有对象。查看this 示例了解更多详情。

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
      super.onSaveInstanceState(savedInstanceState);
      // Save UI state changes to the savedInstanceState.
      // This bundle will be passed to onCreate if the process is
      // killed and restarted.
      savedInstanceState.putBoolean("MyBoolean", true);
      savedInstanceState.putDouble("myDouble", 1.9);
      savedInstanceState.putInt("MyInt", 1);
      savedInstanceState.putString("MyString", "Welcome back to Android");
      // etc.
    }
    
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
      super.onRestoreInstanceState(savedInstanceState);
      // Restore UI state from the savedInstanceState.
      // This bundle has also been passed to onCreate.
      boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
      double myDouble = savedInstanceState.getDouble("myDouble");
      int myInt = savedInstanceState.getInt("MyInt");
      String myString = savedInstanceState.getString("MyString");
    }
    

    或快速处理上述状态的方法。只需简单地使用这个library

    【讨论】:

    • 很高兴听到这个消息。 :)
    猜你喜欢
    • 1970-01-01
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    相关资源
    最近更新 更多