Android Code Snippet Prevent Phone From Sleeping

Description: Prevent the phone from going to black energy saving screen

Select the Phone Library from the [Libs] tab in the IDE

phone.PNG


Add the following in Sub Globals of the Activity you want to keep awake.

B4X:
Sub Globals

Dim pw As PhoneWakeState
         
End Sub

Put the Stay awake code in Sub Activity_Resume of the same Activity. For me I only need the Activity to stay awake if the user is taking a timed test.

B4X:
Sub Activity_Resume

If (comp.gbTimer = True) Then
    pw.KeepAlive(True)
End If

End Sub

Make sure you Turn Off the keep awake stake so you don't waste the battery. The place to do this in Sub Activity_Pause

B4X:
Sub Activity_Pause (UserClosed As Boolean)

If UserClosed Then
    pw.ReleaseKeepAlive
End If

End Sub

Tags: Phone Library, PhoneWakeState, Android OS Function
 
Last edited:

Troberg

Well-Known Member
Licensed User
Longtime User
You can also change the flag Keep_Screen_On of an activity with the reflector library if you don't want to embed the Phone lib in your app:
B4X:
Sub KeepScreenOn(IsEnabled As Boolean)
    'Prevents the screen from sleeping when the current Activity is in the foreground
    Dim r As Reflector
    r.Target = r.GetActivity
    r.Target = r.RunMethod("getWindow")
    Dim FLAG_KEEP_SCREEN_ON As Int = 128
    If IsEnabled Then
        r.RunMethod2("addFlags", FLAG_KEEP_SCREEN_ON, "java.lang.int")
    Else
        r.RunMethod2("clearFlags", FLAG_KEEP_SCREEN_ON, "java.lang.int")
    End If
End Sub

This works for my Galaxy Note, my Galaxy S, my Galaxy Tab 2 and my GF's Galaxy S5. However, it does not work on my Galaxy Tab S. After a while, it goes to sleep, under exactly the same circumstances as the others.

Any ideas?
 

Troberg

Well-Known Member
Licensed User
Longtime User
I have to withdraw some of my previous comment. It doesn't work on any device for me. Darn annoying with a videoplayer that goes to sleep every 20 minutes...

Am I stupid and missing something obvious here?
 

xpectmore

Member
Licensed User
Longtime User
I am so sorry i see your message now ... after 3 years :) but still :
you should compile that and when you run that you should see a quick window that desappear and a red eye icon on the top ,left side.
then if you slide the top of your screen in the top of notifications you should read a text as WakeUp,
thanks JohnD !!!

double that! ;)



ps : i use this in conjunction of using b4A-Bridge

------------------------------------------------
UPDATE for anyone use this in conjunction of using b4A-Bridge :
this version will not go to the home no more ,thanks to JOTHA will run b4A Bridge directly !!!
Prevent Phone From Sleeping&run b4a bridge.zip
 

Attachments

  • Prevent Phone From Sleeping.zip
    114.3 KB · Views: 413
  • Prevent Phone From Sleeping&run b4a bridge.zip
    114.7 KB · Views: 585
Last edited:
Top