Android Question How to detect if app is running in background?

artsoft

Active Member
Licensed User
Longtime User
Hi dears!

I know that there are a lot of deprecated APIs since SDK version 29 and above while trying to find out if an app is running in background or in foreground.

This also includes some libs like i. e. UsageStatsManager or code like this:

B4X:
Sub appIsInBackground As Boolean

    Dim ActMan As JavaObject
    Dim R As Reflector
    
    R.Target  =  R.GetContext
    ActMan    =  R.RunMethod2("getSystemService","activity","java.lang.String")
    
    Dim TaskInfo    As JavaObject  =  ActMan.RunMethod     ("getRunningTasks", Array As Object(1))
    Dim CompInfo    As JavaObject  =  TaskInfo.RunMethodJO ("get", Array As Object(0)).GetField("topActivity")
    Dim PackageName As String      =  CompInfo.RunMethod   ("getPackageName", Null)
    
    Log(PackageName.ToLowerCase)
    
    Return Not(PackageName.ToLowerCase.Contains("ba.example"))
    
End Sub


Also permissions like these two here...

B4X:
AddPermission(android.permission.GET_ACCOUNTS)
AddPermission(android.permission.GET_TASKS)

... are deprecated.

In my case, I have to know if my app is in foreground (visible) or not. There is a service in my app which informs the user via screen note that my app is in a so called "protection mode". If the app is in foreground, there is no need to inform the user... only in case my app is in background.

What should I do now ... or could I do?

I am thankful for any help.

Best regards
:)
 

artsoft

Active Member
Licensed User
Longtime User
If using B4XPages:
B4X:
If B4XPages.GetManager.IsForeground Then

Thanks Erel! Yes, this helps. Thanks :)

In case of pure B4A, I found this:

B4X:
Sub IsInBackground As Boolean
    Dim b As Boolean = True
    ' -----------------------------List of activities:
    For Each Act As Object In Array(Main, Test, Test2)
        b = b And IsPaused(Act)
        If (b == False) Then Return b
    Next
    Return b
End Sub

This also helps: In my case Activity Main and Test were loaded. Activity Test2 wasn't loaded. While my app was running, I pressed to home button on my smartphone in order to set my app in the background and yes, this works!

Thanks again and best regards.
 
Upvote 0
Top