I have a background service, and in my app in Settings activity i have a button to turn the service on/off. If i have the service set to off, when the user opens the app i want the service to start, but stay open as long the app is open. When the app closes the service will close with the app. I can do this as long as the user exits from the app normaly, and i mean by pressing Exit. My problem is if the user exits from the app by pressin the home button or something else comes in front and closes my app, on that point i want to detect that the app will close and close the service aswell.
What i tried to do is this:
ActivityManager activityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
boolean isActivityFound = false;
List<RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
for (int i = 0; i < procInfos.size(); i++) {
if (procInfos.get(i).processName.equals("com.myapp")) {
isActivityFound = true;
}
}
if (isActivityFound == false) {
Intent backgroundIntent = new Intent(getApplicationContext(), BackgroundActivity.class);
getApplicationContext().stopService(backgroundIntent);
}
I tried this after i call finish();
or in onDestroy();
but all the time i get isActivityFound = true
.
Is there a chance to get isActivityFound = false
from within this app, and be able to close the service along with the app?