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

9

我在我的安卓应用中有一个后台服务,在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 服务,然后将服务的响应存储在数据库中。

4个回答

6

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

mContext.stopService(new Intent(mContext,
                     MyBackgroundService.class))

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();      
    }

上述代码将会检查用户是否按下了主页按钮。

1
我已经尝试了你的代码,但是当按下主页按钮时,onKeyDown方法没有被调用。 - Ravi Bhandari
你可能需要从后台服务更新用户界面,这可能导致崩溃。如果是这样的话,你需要对活动的上下文进行检查,并在onPause和OnKeyDown方法中将其设为null,然后在更新UI之前再次检查它。 - amit

1
当我们打开其他应用程序时,我们的应用程序(在后台)会从内存中清除,但整个应用程序并没有被移除,只有一些不必要的数据和活动被完成了。
在您的情况下,要更新的活动从内存中清除,当您运行的后台服务尝试更新UI时,它会抛出NullPointerException而崩溃。
因此,请在onCreate()中保存要更新UI的活动的引用,并在finish()方法中将引用设置为null,然后在后台服务中检查此引用,如果不为null,则更新UI,否则不进行更新。
// Global Class for saving the reference
class GlobalReference{
      public static <name_of_your_activity> activityRef;
}

在你的活动中。
 onCreate(){
     GlobalReference.activityRef = this;
 }


finish(){
    GlobalReference.activityRef = null;
}

在您的后台服务中
if( GlobalReference.activityRef != null){
    // update the UI of your activity
}

希望这段代码能解决您的问题。 编程愉快...

0
按下主页按钮会触发OnPause()函数。重写onPause()并调用stopService: mContext.stopService(new Intent(mContext, MyBackgroundService.class))

请检查更新的问题。因为我已经尝试了您的代码,但是当应用程序在后台运行并且其他应用程序正在运行时,仍然会导致应用程序崩溃。 - Ravi Bhandari

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接