androiddelphiandroid-servicedelphi-10.1-berlinandroid-service-binding

How to check if my app is still running in an Android service?


I'm starting to develop an Android sticky service for my app with Delphi 10.1 Berlin, but I haven't found any tutorial or book that get into it, so I'm asking:

Which is the simplest way to detect if my app is still running or has been killed by the OS/user?


Solution

  • You can look for the process id by package name and see if it is still active.

    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> pids = am.getRunningAppProcesses();
    int processid = 0;
    for (int i = 0; i < pids.size(); i++) {
        ActivityManager.RunningAppProcessInfo info = pids.get(i);
        if (info.processName.equalsIgnoreCase("packageNameSearchingFor")) {
           processid = info.pid; //found it, we are running
        } 
    }
    

    Or you can simply store a shared value in public shared pref or database accessible through ContentProvider that is updated when in foreground or background to check. Either way is fine.