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.