0

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?

2 Answers2

0

You need an event handler or check the other possible ways to exit the app, so you can end the service before.
Use a debugger and follow the steps.
Search stackoverflow for "android exit":
Maybe one these helps:
How to exit from the application and show the home screen?
Android - Preventing users without special permissions to exit the application or power off the phone
when a user exit my android app without clicking logout button the user still appears loggedin in my online database

Community
  • 1
  • 1
Leandro
  • 376
  • 5
  • 16
0

You can use a onWindowFocusChanged(boolean hasFocus) to detect when activity lost a focus.

This method fired up when you press a home key, moving top_bar down , etc.

Sergey Shustikov
  • 15,377
  • 12
  • 67
  • 119
  • i do use this in onStop. But how my app works is when any activity loses focus then the app closes. This is triggered even when i navigate from A activity to B. I dont want it to trigger as long as i navigate inside my activities, but only when the app closes – Antonis Lambrianides Apr 15 '14 at 17:15