停止后台服务当应用程序进入后台时

Rav*_*ari 8 android background-service

我在我的Android应用程序中有后台服务,我从MainActivity onResume()方法启动服务,它工作正常.但是当用户按下主页按钮时如何停止服务.因为当前用户按下主页按钮然后应用程序移动到后台然后用户打开一些其他应用程序然后一段时间后调用我的服务方法和app强制停止.Below是我的启动服务代码 -

Intent msgIntent = new Intent(mContext, MyBackgroundService.class);
        startService(msgIntent);
Run Code Online (Sandbox Code Playgroud)

提前致谢.

EDITED

在我的服务中,我使用下面的代码 -

 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();
}
Run Code Online (Sandbox Code Playgroud)

在我的活动中,我使用下面的代码停止服务 -

@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();
}
Run Code Online (Sandbox Code Playgroud)

但我的服务运行,而我使用其他应用程序,它强制停止app.From后台服务我调用一些webservice,然后将服务响应存储在数据库中.

Roh*_*hit 6

在onPause()和onStop()中停止服务

mContext.stopService(new Intent(mContext,
                     MyBackgroundService.class))
Run Code Online (Sandbox Code Playgroud)