默认情况下,我的应用程序设置为方向横向。这导致设备被锁定时出现问题,因为方向将变为纵向(以容纳锁定的屏幕),这反过来强制onResume被调用。发生这种情况时,所有对象都为空,使应用程序容易崩溃。我做了一些更改,以防止崩溃和应用程序工作'确定'。 OK意味着当您从锁定屏幕返回应用程序时,在捕捉到正确方向之前,UI处于纵向方向半秒。
我已经做了解决的事情
一世。添加了对onResume中永远不会为null的所有对象的空检查
II。在清单中添加了android:configChanges="orientation|screenSize"
III。在清单中添加了android:screenOrientation="landscape"
还有什么办法可以让锁定屏幕转换回我的应用程序更平滑,没有闪烁,闪烁或方向变化?
正如我从你的问题中可以理解的那样。你在onResume()
中面对所有对象的null,导致应用程序崩溃。你不能真正避免再次调用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。