我的应用程序通过 Web 服务调用将数据与远程数据库同步。我在 IntentService 中进行这些调用,以便它们可以在后台运行(我称之为 SyncService)。
启动我的 IntentService 的代码如下所示:
Intent intent = new Intent();
intent.setClass(appContext, SyncService.class);
// place additional values in intent
intent.putExtra("data_type", SyncService.ITEM_TRACKING);
intent.putExtra("user_id", intUserId);
// call SyncService
appContext.startService(intent);
这通常看起来很棒。但是,我的一位 friend 也是我应用程序的用户,他经常告诉我他的数据没有同步并显示在我们的网站上。当我在场时,他的设备恰好显示了这些症状。我将他的设备插入我的计算机,这是我发现的:
- 启动 SyncService 的代码(即:上面的代码)被命中。
- 我在 IntentService 的 onHandleIntent 方法中设置了一个断点,它从未被命中。
- 我检查了他设备的运行服务列表,发现 SyncService 在那里并正在运行。有趣的是,它已经运行了大约 20 分钟。我的印象是 IntentService 在没有要处理的 Intent 时自杀了。
- 我强行停止了 SyncService(而不是应用程序),突然之间,onHandleIntent 开始反复受到攻击。就好像所有 Intent 都在设备上的某个地方排队,现在才被扔到 SyncService。
有没有人知道可能是什么问题?你认为这是我的应用程序的问题吗?使用 Android?
再次,我向 Android 传递一条消息,说“启动此 IntentService 或将消息发送到已经运行的 IntentService”。那时,我无法控制。消息永远不会到达 IntentService。一旦我强制退出应用程序,消息就会发送到 IntentService 并完成它的工作。
更新:我认为这段代码很好,但我会把它放上去,因为你们中的很多人可能都想看它。
进入 IntentService 的每个 Intent 都有一个 Extra 表示对我发出的调用的“类型”(即:我调用这个网络服务还是那个网络服务等)。当 Intent 进入 IntentService 时,我会检查“类型”,如果队列中已经有该类型的 Intent,我会向它添加一个名为“skip”的 Extra,因此,当它到达时,我不会t 执行搜索(基本上 IntentService 可以构建很多 Intent,并且在 20 秒前调用 this web 服务时调用 this web 服务没有意义)。它基本上可以防止应用程序向网站发送垃圾邮件。
重要的是要注意无论如何都不会命中此代码(一旦问题开始出现)。 onStartCommand 在应用被终止之前不会被调用
@Override
public int onStartCommand (Intent intent, int flags, int startId) {
// here be dragons
// overriding this method and adding your own code is dangerous. i've wrapped
// my code in a try/catch because it is essential that the super method be called
// every time this method is entered. any errors in my code should not prevent this
// or the app will explode.
try {
if (flags == 0 && intent != null && intent.hasExtra("data_type")) {
Integer intDataType = intent.getExtras().getInt("data_type");
if (!mCurrentTypes.containsKey(intDataType)
|| !mCurrentTypes.get(intDataType)) {
mCurrentTypes.put(intDataType, true); // put this type in the list and move on
}
else {
intent.putExtra("skip", true); // mark this Intent to be skipped
}
}
}
catch (Exception e) {
// Log.e("Error onStartCommand", "error: " + e);
}
return super.onStartCommand(intent, flags, startId);
}
private void processIntent(Intent intent) {
// do stuff if no "skip" Extra
mCurrentTypes.put(intDataType, false);
}
最佳答案
肯定有一些东西可以让您的服务在您 friend 的设备上运行。如果是这样,对该 Intent 服务的所有后续调用都将排队,直到当前调用完成。如果它没有完成,那么你将得到你所拥有的:下一个服务将不会启动。
你应该仔细检查:
- 你给网络操作适当的超时
- 您为网络连接操作设置适当的超时时间
- 线程之间没有竞争条件。
- 您记录服务内部可能发生的任何异常,您不想丢失此类信息。
之后,如果您认为一切正常:只需记录服务所做的事情并使用一些错误报告机制使其自动从您 friend 的设备发送。一个简单的解决方案可能是使用 bugsense 或等同物。
接下来,放置某种看门狗:一个线程将继续运行直到您的服务停止(您只需告诉您的线程在服务停止时停止)。过了某个时间限制后,该线程将不得不停止您的服务。
这个看门狗线程可以放在服务本身内部,也可以放在外部,尽管这样放置起来可能更复杂。
关于android - IntentService 未触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11347038/