我在我的安卓应用中有一个后台服务,在MainActivity的onResume()方法中启动服务,它可以正常工作。但是当用户按下Home键时,如何停止服务呢?因为当前情况下,当用户按下Home键后,应用程序移至后台,然后用户打开其他应用程序后,过一段时间我的服务方法就会被调用,应用程序强制停止。以下是我的启动服务代码 -
Intent msgIntent = new Intent(mContext, MyBackgroundService.class);
startService(msgIntent);
感谢您的提前帮助。
编辑后:
在我的服务中,我使用以下代码 -
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();
}
在我的活动中,我使用以下代码来停止服务 -
@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();
}
但是当我使用其他应用程序时,我的服务仍在运行,并强制停止该应用程序。我从后台服务调用一些 Web 服务,然后将服务的响应存储在数据库中。