App seems to stop working when the screen goes to sleep

后端 未结 3 2061
离开以前
离开以前 2020-12-05 15:59

I have a CPU intensive long-running operation (a few hours) that I am using AsyncTask to perform. As it continues, it updates a progressbar on the screen to show what percen

3条回答
  •  既然无缘
    2020-12-05 16:58

    My 2 cents on this old post, in case it might help someone. If all you want is to prevent your screen from going to sleep, there's a simple solution that does not require a permission from the user - and it's just 2 lines of code:

    // prevent the screen from sleeping
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    
    // do your stuff
    
    // don't forget to re-enable the screen time-out so it won't stay awake from now on
    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    

    An important note: it can only be called within an Activity - not from other app components. more details can be found here.

提交回复
热议问题