【问题标题】:How do I cancel all pending intents that are qued for intent Service如何取消排队等待意向服务的所有待处理意向
【发布时间】:2011-12-02 14:58:10
【问题描述】:

我有一个由用户和我的应用程序自动查询的意图服务。当用户退出我的应用程序时,我需要能够杀死所有待处理的意图,但我似乎无法让它工作。我已经尝试过 stopService() 和 stopself(),但是在用户注销后,意图会继续触发 intentservice。我会尝试获取意图的 id,但这很困难,因为每次意图服务启动时,保存意图 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
}

【问题讨论】:

  • android开发者似乎无法使用实际的intent Que for和IntentService。

标签: android kill intentservice


【解决方案1】:

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

我能想到几个选项,您可以尝试看看它们是否符合您的需要。

  1. 复制 IntentService 代码以对其进行自己的修改,以便删除待处理的消息。看起来有人在这里取得了一些成功:Android: intentservice, how abort or skip a task in the handleintent queue
  2. 除了复制所有 IntentService 代码之外,您还可以像普通服务一样绑定到它(因为 IntentService 扩展了服务),因此您可以编写自己的函数来删除待处理的消息。该链接中也提到了这一点。
  3. 改为将 IntentService 重写为常规服务。使用此选项,您可以更好地控制添加和删除消息。

我在使用 IntentService 时遇到过类似的情况,但最终我只是将其转换为 Service。这让我可以同时运行这些任务,并在需要清除它们时取消它们。

【讨论】:

  • 我会将其标记为已修复,因为这是我能想到的最佳答案,即使我们决定采用更容易的不同方法。谢谢
【解决方案2】:

这里 When should I free the native (Android NDK) handles? 是具有 cancelQueue() 方法的 HangAroundIntentService 类。 该类也有方法

public static Intent markedAsCancelIntent(Intent intent)

将意图转换为取消意图,并且

public static boolean isCancelIntent(Intent intent).

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

【讨论】:

    【解决方案3】:

    只是一个想法,但是在您的 onhandleintent 内部,您是否可以有一个参数来检查应用程序是否正在运行,如果没有,则不要运行代码?例子。在你的应用程序开始时,你可以有一个静态变量

    boolean appRunning;
    

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

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

    只是一个想法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-21
      • 2013-08-05
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多