4

我有一个由用户和我的应用程序自动查询的意图服务。当用户注销我的应用程序时,我需要能够杀死所有待处理的意图,但我似乎无法让它工作。我已经尝试过 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
}
4

3 回答 3

4

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

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

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

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

于 2011-12-02T23:07:43.207 回答
0

在这里 我应该什么时候释放本机(Android NDK)句柄?HangAroundIntentService具有方法的类cancelQueue()。该类也有方法

public static Intent markedAsCancelIntent(Intent intent)

将意图转换为取消意图,以及

public static boolean isCancelIntent(Intent intent).

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

于 2012-09-25T13:30:54.933 回答
0

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

boolean appRunning;

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

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

只是一个想法

于 2016-06-05T02:11:47.350 回答