Android Question StartActivity from Service


Well-Known Member
Licensed User
At boot startup, my service need to call Main if enabled by user. I saw hint with StartActivity stating "you should usually not call StartActivity from Service". How else am i going to start up Main? Is StartActivity the best method?


Licensed User
Note that starting from Android 10 it is no longer possible to start activities while the app is in the background (foreground service will not help here).
One (of many) exception to this restriction mentioned in the Android docs (here: is:
The app has been granted the SYSTEM_ALERT_WINDOW permission by the user.
And (not unusual) @Erel has already supplied code for how to do this here:
This solutions has been tested and confirmed to be working by @Jmu5667

Note: For completeness: This particular exception has another exception:


Well-Known Member
Licensed User
This solutions has been tested and confirmed to be working by @Jmu5667
Yes indeed, you need to add this to the manifest file.

And this

Sub Activity_Resume
   Dim p As Phone
   If p.SdkVersion > 28 Then
       Dim c As cls_request_drawover_persmission
       Wait For (c.GetPermission) Complete (Success As Boolean)
   End If

end sub
cls_request_drawover_permission @OliverA

Sub Class_Globals

   Private ion As Object

End Sub

Public Sub Initialize

End Sub

Public Sub GetPermission As ResumableSub

   Dim jo As JavaObject
   Dim ctxt As JavaObject
   ' // we already have it
   If jo.RunMethod("canDrawOverlays", Array(ctxt)) = True Then
       Return True
   End If
   ' // request it
   Dim i As Intent
   i.Initialize("android.settings.action.MANAGE_OVERLAY_PERMISSION", "package:" & Application.PackageName)
   Wait For ion_Event (MethodName As String, Args() As Object)
   Return jo.RunMethod("canDrawOverlays", Array(ctxt))

End Sub

Private Sub StartActivityForResult(i As Intent)
   Dim jo As JavaObject = GetBA
   ion = jo.CreateEvent("anywheresoftware.b4a.IOnActivityResult", "ion", Null)
   jo.RunMethod("startActivityForResult", Array As Object(ion, i))
End Sub

Private Sub GetBA As Object
   Dim jo As JavaObject = Me
   Return jo.RunMethod("getBA", Null)
End Sub
Obviously credit to @Erel for providing the necessary code etc.


Last edited: