Android Question Detect opened application

carchek

Member
Licensed User
Longtime User
hi guys!
I am having a problem how to detect opened application, by my process in the background; example:
Users runs my app, then the process is started with STICKY artibutes. Now I would like, that my Process I call it "background" detects opened appliaction and puts on notification for example: If user opens Facebook and is checking it out (FB app is on the screen), user will get notification "You're are reading Facebook, here is blahblahblah...".
Thanks,
Gregor
 

stevel05

Expert
Licensed User
Longtime User
Try this as a service, or incorporate it into your existing service based on code found here http://stackoverflow.com/questions/...he-current-foreground-activity-from-a-service


B4X:
#Region  Service Attributes
    #StartAtBoot: False
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim Timer1 As Timer
    Dim ActMan As JavaObject
  
End Sub
Sub Service_Create
    Timer1.Initialize("Timer1",1000)
End Sub

Sub Service_Start (StartingIntent As Intent)
    Timer1.Enabled = True
    Dim R As Reflector
    R.Target=R.GetContext
    ActMan = R.RunMethod2("getSystemService","activity","java.lang.String")
End Sub

Sub Service_Destroy
    Timer1.Enabled = False
End Sub
Sub Timer1_Tick
    'From http://stackoverflow.com/questions/3873659/android-how-can-i-get-the-current-foreground-activity-from-a-service
    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)
  
End Sub

You need to add the line:

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

to your Manifest File.
 
Last edited:
Upvote 0
Top