-1

I want to start a service when I press the home button or just press back (when the app is in the background but not killed) how can I do a function that checks that ? thanks to all

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
ozmor
  • 1
  • in onPause of your MainActivity, you start the service? – Mohammed Atif Mar 30 '17 at 14:27
  • Possible duplicate of [How to detect when an Android app goes to the background and come back to the foreground](http://stackoverflow.com/questions/4414171/how-to-detect-when-an-android-app-goes-to-the-background-and-come-back-to-the-fo) – X3Btel Mar 30 '17 at 14:28
  • You pretty much should not do that. this is my favorite answer on this question- http://stackoverflow.com/a/19920353/4810277 – X3Btel Mar 30 '17 at 14:29
  • i just want to start a timer for when he quits it so i send him notification after some time now i have service when he kills the app but it doesnt work if its still in background – ozmor Mar 30 '17 at 14:38
  • 1
    Welcome to Stack Overflow! Please take a tour [How do I ask a good question?](//stackoverflow.com/help/how-to-ask) and [How to create a Minimal, Complete, and Verifiable example](//stackoverflow.com/help/mcve). – Olaia Mar 30 '17 at 14:51

4 Answers4

0

Use Foreground service using startForeground() method and START_STICKY flag. In breif, you have to say to the user 'my app is still working'.

Or the other implementation is to use AlarmManager if you want to charge the task for the future.

Vyacheslav
  • 26,359
  • 19
  • 112
  • 194
0

You can implement Application.ActivityLifecycleCallbacks and attach it to your Application to now when your app is in background. Here is Foreground example.

John
  • 1,304
  • 1
  • 9
  • 17
0

You need a BaseActivity,and all other Activities must extend this BaseActivity:

as @Shoad said but the method that triggers is

    public class BaseActivity extends Activity {
     @Override
    protected void onPause() {

//Start Service or do what you want

    }
    }

Couldn't succed comment down

g7pro
  • 817
  • 1
  • 6
  • 11
-1

You need a BaseActivity,and all Activities must extand this BaseActivity:

public class BaseActivity extends Activity {
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
        startService(new Intent(this, AService.class));
        //maybe you need check the AService is running here```
    }
    return super.onKeyDown(keyCode, event);
}
}
Shoad
  • 192
  • 1
  • 6