简体   繁体   English

setKeepScreenOn / FLAG_KEEP_SCREEN_ON的正确方法

[英]Correct method for setKeepScreenOn / FLAG_KEEP_SCREEN_ON

I am using the method setKeepScreenOn(true) and haven't been able to figure out how to call this in relation to the current Activity (which has a content view set). 我使用方法setKeepScreenOn(true),并且无法弄清楚如何相对于当前Activity(具有内容视图集)调用它。 I've been able to get it to work by calling it on one of my buttons which is always present in the view, but this feels wrong - and I'm sure there must be a way to get around this. 我已经能够通过在我的一个按钮上调用它来实现它,它总是出现在视图中,但这感觉不对 - 而且我确信必须有办法解决这个问题。 I tried referencing the current focus like this: 我尝试引用当前的焦点,如下所示:

getCurrentFocus().setKeepScreenOn(true);

but that threw a NullPointerException. 但是抛出了NullPointerException。 Maybe there was no current focus. 也许目前没有焦点。 So, can anyone tell me how I can reference the view class which I am working inside? 那么,有人能告诉我如何引用我在里面工作的视图类吗? Thanks :) 谢谢 :)

Try this answer : 试试这个答案

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

getWindow is a method defined for activities, and won't require you to find a View first. getWindow是为活动定义的方法,不需要您首先查找View

As Hawk said but poorly explained. 正如霍克所说,但解释不佳。

You can also use FLAG_KEEP_SCREEN_ON in your XML layout file. 您还可以在XML布局文件中使用FLAG_KEEP_SCREEN_ON

Note the android:keepScreenOn="true" 注意android:keepScreenOn="true"

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:keepScreenOn="true"
    android:orientation="vertical" >

    <!-- whatever is in your layout -->

</LinearLayout>

I've now written all the choices for keeping the screen on up into a blog post: 我现在写了所有选择,以保持屏幕上的博客文章:
http://blog.blundellapps.com/tut-keep-screen-onawake-3-possible-ways/ http://blog.blundellapps.com/tut-keep-screen-onawake-3-possible-ways/

在XML中设置android:keepScreenOn

If you are doing it on a class extends View. 如果您在类扩展View上执行此操作。 You can simple: 你可以简单:

this.setKeepScreenOn(true);

According to Google Docs for android Developers you've two ways to do this : 根据Google Docs for android Developers,您有两种方法可以做到这一点:

First way : 第一种方式:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}

Second way is to add in your xml file layout this attribute: android:keepScreenOn="true" 第二种方法是在你的xml文件布局中添加这个属性: android:keepScreenOn="true"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM