如何取消排队等待intentService的所有待处理意图

时间:2011-12-02 14:58:11

标签: android kill intentservice

我有一个intentservice,由用户和我的应用程序自动查询。当用户退出我的应用程序时,我需要能够杀死所有挂起的意图,但我似乎无法使其工作。我已经尝试过stopService()和stopself(),但是在用户注销后意图继续触发intentservice。我会尝试获取intent的id,但这很困难,因为每次intentservice启动时,持有intent id的变量都是空的。这是我的意向服务代码:

public class MainUploadIntentService extends IntentService {
private final String TAG = "MAINUPLOADINTSER";
private GMLHandsetApplication app = null;
private SimpleDateFormat sdf = null;
public boolean recStops = true;

public MainUploadIntentService() {
    super("Main Upload Intent Service");

    GMLHandsetApplication.writeToLogs(TAG,
            "GMLMainUploadIntentService Constructor");

}

@Override
protected void onHandleIntent(Intent intent) {
GMLHandsetApplication.writeToLogs(TAG, "onHandleIntent Started");
if (app == null) {
    app = (GMLHandsetApplication) getApplication();
}
uploadData(app);
    GMLHandsetApplication.writeToLogs(TAG, "onHandleIntent Finished");
}

@Override
public void onDestroy() {
GMLHandsetApplication.writeToLogs(TAG, "onDestroy Started");
app = null;
    stopSelf();
    GMLHandsetApplication.writeToLogs(TAG, "onDestroy completed");
}

public void uploadData(GMLHandsetApplication appl) {
    //All of my code that needs to be ran
}

3 个答案:

答案 0 :(得分:4)

不幸的是,我不认为使用标准的IntentService方法可以实现这一点,因为它没有提供在它已经运行时中断它的方法。

我可以想到一些选项,你可以尝试看看它们是否符合你的需要。

  1. 复制IntentService代码以对其进行自己的修改,以便您删除待处理的消息。看起来有人在这里取得了一些成功:Android: intentservice, how abort or skip a task in the handleintent queue
  2. 您可能也可以像普通服务一样绑定所有IntentService代码,而不是复制所有IntentService代码(因为IntentService扩展了Service),因此您可以编写自己的函数来删除待处理的消息。该链接中也提到了这一点。
  3. 改为将IntentService重写为常规服务。使用此选项,您可以更好地控制添加和删除邮件。
  4. 我听到类似的情况,我使用的是IntentService,最后我将其转换为服务。这让我可以同时运行任务,并在需要清除它们时取消它们。

答案 1 :(得分:0)

下面 When should I free the native (Android NDK) handles?是具有方法HangAroundIntentService的{​​{1}}类。 该类还有方法

cancelQueue()

将意图转换为取消意图,

public static Intent markedAsCancelIntent(Intent intent)

该课程基于开源的Google代码。

答案 2 :(得分:0)

只是一个想法,但你的onhandleintent内部可以有一个参数,检查应用程序是否正在运行,如果没有,然后不运行代码?例。在应用程序的开头,您可以使用静态var

boolean appRunning;

接下来在你的意图的处理中,当你将appRunning设置为false时,在onPause或onDestroy活动之后,你可以将onhandleintent代码包装在一个布尔值中:

 protected void onHandleIntent(final Intent intent) {
     if(MainActivity.appRunning){
       ...
     }
}

只是一个想法