[英]Android Life Cycle Issue
我正在开发一个手电筒应用程序,我希望将它设置为用户打开应用程序时屏幕亮度变满的地方。 我已经设置了一个复选框首选项来执行此操作,但有一个小问题。 见下面的代码:
<CheckBoxPreference
android:defaultValue="true"
android:key="pref_brightness"
android:summary="When checked, brightness will raise to highest level on main activity."
android:title="@string/pref_5" />
这是首选项布局的xml文件中的复选框代码。
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean box = getPrefs.getBoolean("pref_brightness", true);
if (box == true) {
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = 100 / 100.0f;
getWindow().setAttributes(lp);
}
这是我在MainActivity.java文件中访问首选项的地方。 这是在onCreate()方法中。
现在我的问题是......当我打开应用程序时,会检查该框(除非用户更改)并且亮度最大化应该如此。 但是,当我进入首选项并取消选中该框时,然后按“后退”按钮,该框保存但不会对主要活动产生任何影响。 如果我更改了框并按下操作栏上的“向上”按钮,一切都很好。 按下后退按钮时为什么不起作用? 我尝试使用onBackPressed()但似乎没有解决这个问题。
我做了你说的,它仍然无法正常工作。 如果未选中该框并且我检查它,按下后退按钮,它可以工作,但如果我再次将其更改回来,再次按回来,它不会保存。 这是您的建议代码:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean box = getPrefs.getBoolean("pref_brightness", true);
if (box == true) {
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = 100 / 100.0f;
getWindow().setAttributes(lp);
}
super.onWindowFocusChanged(hasFocus);
}
感谢帮助,
安德鲁
更改属性的代码不应该在onCreate()
内。尝试使用onStart()
。
如果在onCreate()
运行此代码,则只会在创建Activity时调用一次。 你需要在其他地方运行它。 我推荐onWindowFocusChanged()
。 (您可以使用onStart()
或onResume()
,但这些不会考虑锁定屏幕。)
解决了!
我只需要一个完整的if语句,如下所示:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean box = getPrefs.getBoolean("pref_brightness", true);
if (box == true) {
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = 100 / 100.0f;
getWindow().setAttributes(lp);
}
else{
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.screenBrightness = -1;
getWindow().setAttributes(lp);
}
super.onWindowFocusChanged(hasFocus);
}
现在,如果选中复选框,则将主活动的亮度更改为已满,但如果未选中,则将用户的亮度设置为其设置。
感谢Karakuri的帮助以及Nizam !
安德鲁
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.