从服务的Android更新活动 [英] Android update Activity from a Service
问题描述
我这样就失去了与Android的通知和服务的所有工作流程。我sceneario是这样的:
I'm so lost with all that workflow of notifications and services in Android. My sceneario is this:
我有一个通过Web服务使用JSON-RPC通信到MySQL数据库的Android应用程序。从服务中检索到的数据将被显示在应用程序
I have an Android application that communicate to a MySQL database through a web-service using JSON-RPC. The data retrieved from the service will be displayed in the application.
中的数据将随着时间的推移得到更新,所以应用程序需要监听的这种变化,如果变化发生,显示通知和更新应用程序中显示的数据。
The data will get updated over time, so the application needs to listen for changes of this and, if a change occur, show a notification and update the data displayed in the app.
要监听的变化,我将需要运行一个无限(直到应用程序被破坏或者直到应用程序毁坏它)线程不时会请个网络服务,将返回变化的方法自上次检查。
To listen for changes I will need to run an "infinite"(until the app is destroyed or maybe until the app destroys it) thread that from time to time will call a method on th web-service which will return the changes since the last check.
更新:好吧,我一直在用努力服务
和 IntentService
,但其中不符合我的需求:一个服务
在主线程中执行,所以如果我执行有一个无限循环我的应用程序将冻结, IntentService
有它的自己的工作线程但与App没有交际,我需要它,或者至少我需要一种方法来知道,如果应用程序是在前台(在这种情况下,通知将不弹出,但该数据将被传递和更新)或在背景(中间体此情况下,通知将弹出并点击它会直接把用户到应用与更新的数据)
UPDATE: Ok, I have been trying using Service
and IntentService
, but non of them fits my needs: a Service
execute in the Main Thread, so If I perform an infinite loop there my app will freeze, IntentService
has it's own worker thread but there is no comunication with the App, and I need it, or at least I need a way to know if the app is in foreground (in this case the notification will not popup but the data will be passed and updated) or in background (int this case the notification will pop up and on click it will direct the user to the app with the updated data)
推荐答案
好吧,大量的试验,并感谢这里给出的信息后,我终于找到了一种方法来处理这个问题,所以我会在这里分享:
Ok, after a lot of testing and thanks to the info given here I finally found a way to handle with the issue, so I will share it here:
在 IntentService
我有一个公共静态 的AtomicBoolean
来控制结束循环并能够停止服务。
On the IntentService
I have a public static AtomicBoolean
to control the end of the loop and be able to stop the service.
然后再确定是否活动
是在前台与否我使用的方法这里建议的 http://stackoverflow.com/a/5504711/3107765
Then to determine if the Activity
is in foreground or not I use the method suggested here http://stackoverflow.com/a/5504711/3107765
使用我使用static修饰符存在的差异,这样我就可以从服务检查。
With the difference that I use the static modifier there, so I can check it from the service.
如果活动是在前台我送,因为它是欧盟这里建议广播。博士否则我使用,一旦点击就会让用户在活动的通知。
if the activity is in foreground I send a broadcast as it was suggested here by Eu. Dr. otherwise I use a notification that once clicked will let the user to the activity.
这篇关于从服务的Android更新活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!