I try to set the screen to always on however I cant figure out how to do it within a fragment. I have tried to get access to the ViewPager but it returns with a null value. I want the screen to be on for the whole application but it should be able to be changed by the user within the settings of the app.

Here is my code from within my fragment:

private void setIsAlwaysOn(boolean b)
{
    ViewPager pager = (ViewPager)getView().findViewById(R.id.pager);
    pager.setKeepScreenOn(b);

    sharePropertiesEditor.putBoolean(sp_alwaysOn, b);
    sharePropertiesEditor.commit();
}

I get a nullpointerexception at line 4 of the visible code above.

有帮助吗?

解决方案

Yeah. Can't you use this?

getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

For Kotlin, use:

activity?.window?.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top