Stop background Service When application goes to background
Asked Answered
P

4

9

I have background service in my android app,i start service from MainActivity onResume() method and it is work correctly.But how can i stop service when user press home button.Because currently when user press home button then application move to background and then user open some other app then after some time my service method is called and app force stop.Below is my code for start service -

Intent msgIntent = new Intent(mContext, MyBackgroundService.class);
        startService(msgIntent);

Thanks in Advance.

EDITED

In My Service i use below code -

 public void callAsynchronousTask() {
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {       
    @Override
    public void run() {
        handler.post(new Runnable() {
            public void run() {       
                try {
                    callWebservice();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
};
timer.schedule(doAsynchronousTask, START_DELAY, DELAY);
 }

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    callAsynchronousTask();
    return Service.START_NOT_STICKY;
}

@Override
public void onCreate() {
    mContext = this;
    super.onCreate();
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    super.onDestroy();
    if(timer!=null){
        timer.cancel();
    }
    stopSelf();
}

in my activity i use below code for stop service -

@Override
protected void onStop() {
    try{
         stopService(new Intent(this, MyBackgroundService.class));
         isServiceRunning = false;
    }
   catch(Exception e){
    e.printStackTrace();
   }
    super.onStop();
}

@Override
protected void onPause() {
    try{
         stopService(new Intent(this, MyBackgroundService.class));
         isServiceRunning = false;
    }
    catch(Exception e){
        e.printStackTrace();
    }
    super.onPause();
}

but my service is run while i use some other app and it force stop app.From background service i call some webservice and then store response of service in database.

Patrizio answered 18/10, 2014 at 10:42 Comment(0)
C
6

Stop the service in onPause() and onStop()

mContext.stopService(new Intent(mContext,
                     MyBackgroundService.class))
Charily answered 18/10, 2014 at 10:50 Comment(0)
G
2
@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode==KeyEvent.KEYCODE_HOME){
            Log.e("home key pressed", "****");   
            // write your code here to stop the activity
            enter code here
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        Log.e("home key pressed on pause", "****");
        // write your code here to stop your service 
        super.onPause();      
    }

the above code will keep check if user have pressed the home button or not.

Gera answered 18/10, 2014 at 11:15 Comment(2)
I have try your code but when home button is pressed then onKeyDown method is not called.Patrizio
you must be updating ui from your background service which may be causing the crash. if so you need to apply a check for the context of your activity and make it null on onPause and Onkey down method then before updating ui make check for it.Gera
L
1

when we open the other applications then our application(which was in background) gets cleared from the memory However the whole application does not removed but the some unwanted data and activities get finished. In your case the activity which is to be updated gets cleared from the memory and your running background service when try to update the UI then it gets crashed by throwing NullPointerException.

So please saved the Reference of the activty(whose UI is to be updated) in onCreate() and set the reference to null in finish() method then check this reference in the background service if it is not null then update the UI otherwise no updation.

// Global Class for saving the reference
class GlobalReference{
      public static <name_of_your_activity> activityRef;
}

in your activity

 onCreate(){
     GlobalReference.activityRef = this;
 }


finish(){
    GlobalReference.activityRef = null;
}

In your background service

if( GlobalReference.activityRef != null){
    // update the UI of your activity
}

Hope this code will solve your issue. Happy Coding...

Lucindalucine answered 20/10, 2014 at 6:1 Comment(0)
A
0

press Home Button cause OnPause() function. Override onPause() and call stopService: mContext.stopService(new Intent(mContext, MyBackgroundService.class))

Ariminum answered 18/10, 2014 at 10:57 Comment(1)
Please check updated question.Because i have try your code but still app crash while app is in background and some other app is running.Patrizio

© 2022 - 2024 — McMap. All rights reserved.