getWindow()中的NullpointerException.getAttributes();

时间:2014-06-15 08:13:12

标签: java android screen-brightness

我正在尝试在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)

有人早些时候遇到过这个问题吗?

2 个答案:

答案 0 :(得分:1)

当我拨打transaction.commit()时,我遇到了这个问题。

将其更改为transaction.commitAllowingStateLoss()后问题就消失了。

答案 1 :(得分: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);
}

如果你想更好地使用这种方法来查看This thread,因为活动的传递参考不是一个好方法。

但是我认为你的问题最好是使用SharedPreference来保存A类的亮度并在B类中使用它,

你可以看到This Question了解如何在android中使用SharedPreference来获取设置和编辑值。

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