android - IntentService 陷入困境

标签 android service android-intent

我构建了一个应用程序,它使用 IntentService 来操作应用程序的数据库和调用网络服务。

例子:

我有一个 Activity ,它是一个项目列表。此列表由 CursorAdapter 填充。每个项目都有一个复选框,列表按选中排序(顶部未选中的项目,底部选中的项目)。当一个项目的复选框被选中时,我向我的 IntentService 发送一个 Intent 告诉它在数据库表中为该项目标记选中的列,然后广播一条消息,Activity 看到它并重新查询 Cursor。

当我使用移动设备并开始快速选中复选框时,应用程序基本上挂起。 UI 不会挂起,但后台的 IntentService 会挂起。我可以判断是因为屏幕上的光标没有刷新。

据我了解,传递给 IntentServices 的 Intents 不是异步处理的。那是对的吗?它的行为几乎就像我需要使用信号量一样,但我不明白为什么要单独排队和处理 Intents。

假设我勾选了 3 个复选框;所以有 3 个 Intents 排队。在第一个之后,我广播了一条消息,Activity 收到该消息,告诉它重新查询它的光标。潜在的问题可能是因为我在处理第二个 Intent(更新表中的另一行)的同时重新查询 Cursor?查询 Cursor 发生在 UI 线程上。

^ 我认为这是我的问题。我应该用什么来同步这个?信号量?有人可以指出一些文档/示例吗?

另一个潜在的问题是,如果我的 Activity 管理表上的 Cursor 怎么办?我的 IntentService 也从同一张表中查询游标。我遇到过这种情况,因为我的 IntentService 正在遍历 Cursor 中的每一行以查找要发送到 Web 服务的项目。不过,只要游标不同时查询,我认为这不会成为问题?

还有人有其他想法吗?

最佳答案

When an item's checkbox is checked, I send an Intent to my IntentService telling it to flag the checked column in the database table for that item, then a message is Broadcasted, the Activity sees it and re-queries the Cursor.

有点“别克打苍蝇”的感觉。

It is my understanding that Intents passed to IntentServices are not processed asynchronously. Is that correct?

IntentService 中的

onHandleIntent() 在后台线程上调用,startService() 始终是异步的。

It's behaving almost like I need to be using semaphores, but I can't understand why if Intents are queued and processed individually.

单个 IntentIntentService 依次排队和处理。

Could a potential problem be because I'm requerying the Cursor at the same time I'm processing the second Intent (updating another row in the table)?

这当然没有帮助。

What should I use to synchronize this? Semaphores?

我只是使用synchronized(someStaticDataMember),但信号量应该可以工作。

Though I wouldn't think this would be a problem so long as the Cursors don't query at the same time?

直到触摸光标(例如,moveToFirst()getCount()),才会执行实际查询。之后,只要查询结果集小于1MB,结果就全部在Cursor中。

我部分同意 Christopher 的观点:使用一些日志记录来弄清楚到底发生了什么,并考虑使其更轻量级(例如,用于数据库写入的 AsyncTask 而不是 IntentService) .

关于android - IntentService 陷入困境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3875880/

相关文章:

java - 服务以错误的时间间隔执行短信

Delphi服务应用程序通过Application.Run方法获取过去

java - 应用程序在从一项 Activity 转移到另一项 Activity 时停止

java - Android教程切换第一种情况方法无法访问

maven - 向 Team Services 构建代理添加 maven 功能

java - 尝试关闭 HttpURLConnection

android - 在 Activity 之间传递类的实例

android - 从自定义 ListView 中的 TextView -w/Button 获取文本

android - 如何将数据从 Android 应用程序发送到服务器?

android - 如何更改 phoneGap ( Apache Cordova ) Api