0

我正在尝试获取 Android 中的屏幕亮度。

场景是这样的,A类调用B类的函数:

A类:

if(condition is true){
  ClassB.function();
}

B类:

function(){
WindowManager.LayoutParams screenBrightness = getWindow()
                    .getAttributes();
screenBrightness.screenBrightness = 1;
screenBrightness.flags |= WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
screenBrightness.flags |= WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
screenBrightness.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
getWindow().setAttributes(screenBrightness);
}

收到的异常如下:

06-15 13:36:30.476: E/AndroidRuntime(8873): FATAL EXCEPTION: main
06-15 13:36:30.476: E/AndroidRuntime(8873): java.lang.NullPointerException
06-15 13:36:30.476: E/AndroidRuntime(8873):     at function(B.java:68)
06-15 13:36:30.476: E/AndroidRuntime(8873):     at something.run(A.java:104)
06-15 13:36:30.476: E/AndroidRuntime(8873):     at android.os.Handler.handleCallback(Handler.java:587)
06-15 13:36:30.476: E/AndroidRuntime(8873):     at android.os.Handler.dispatchMessage(Handler.java:92)
06-15 13:36:30.476: E/AndroidRuntime(8873):     at android.os.Looper.loop(Looper.java:130)
06-15 13:36:30.476: E/AndroidRuntime(8873):     at android.app.ActivityThread.main(ActivityThread.java:3701)
06-15 13:36:30.476: E/AndroidRuntime(8873):     at java.lang.reflect.Method.invokeNative(Native Method)
06-15 13:36:30.476: E/AndroidRuntime(8873):     at java.lang.reflect.Method.invoke(Method.java:507)
06-15 13:36:30.476: E/AndroidRuntime(8873):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
06-15 13:36:30.476: E/AndroidRuntime(8873):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:624)
06-15 13:36:30.476: E/AndroidRuntime(8873):     at dalvik.system.NativeStart.main(Native Method)

有没有人之前遇到过这个问题?

4

2 回答 2

1

我打电话时遇到了这个问题transaction.commit()

改了之后transaction.commitAllowingStateLoss()问题就解决了。

于 2018-01-09T01:09:10.333 回答
0

尝试以下代码:

if(condition is true){
  ClassB.function(this);
}

功能是:

public static void function(Activity activity){

    WindowManager.LayoutParams screenBrightness = activity.getWindow()
                    .getAttributes();
    screenBrightness.screenBrightness = 1;
    screenBrightness.flags |= WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON;
    screenBrightness.flags |= WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD;
    screenBrightness.flags |= WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
    activity.getWindow().setAttributes(screenBrightness);
}

如果您想更好地使用此方法来查看此线程,因为传递活动引用不是一个好方法。

但正如我看到的那样,您的问题最好使用 SharedPreference 来保存 A 类中的亮度并在 B 类中使用它,

您可以查看此问题以了解如何SharedPreference在 android 中使用,获取设置和编辑值。

如果您对此有任何疑问,可以问我。

于 2014-06-15T08:36:54.067 回答