与来自服务的活动 (LocalService) 通信 - Android 最佳实践 [英] Communicate with Activity from Service (LocalService) - Android Best Practices
问题描述
常见场景 - 使用后台服务轮询服务器的活动.
服务将通过 AlarmManager 定期运行,并为 Activity 执行任务(用户点击按钮,从服务器获取一些东西).
我想了解这里的最佳做法.我认为最好的设计是 Android LocalService 示例:http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
但是在示例中,Activity 引用了 mBoundService
Activity,但没有反向连接(Service 无法调用 Activity)..>
服务调用活动的最佳方式是什么?
我是否使用意图、广播接收器、消息?如何?
我认为最好的设计是 Android LocalService 示例:http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
我不会.使用您能忍受的尽可能松散的联轴器.因此,平均而言,目标是使用 startService()
的命令模式,而不是使用 bindService()
的绑定模式.值得注意的是,在处理配置更改(例如屏幕旋转)时,绑定有点麻烦.
服务调用活动的最佳方式是什么?我是否使用意图、广播接收器、消息?怎么样?
参见从服务通知活动
Common scenario - Activity with a background Service to poll server.
The Service will run periodically via AlarmManager and also perform tasks for the Activity (user hits a button, go fetch something from server).
I'd like to know the best practices here. I think the best design would be the Android LocalService example: http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
However in the example the Activity has a reference to the activity mBoundService
but there is no reverse connection (the Service has no way to call the Activity).
What is the best way for the Service to call the Activity?
Do I use Intents, BroadcastReceivers, Messages? How?
I think the best design would be the Android LocalService example: http://developer.android.com/reference/android/app/Service.html#LocalServiceSample
I wouldn't. Use the loosest possible coupling you can stand. Hence, on average, aim for the command pattern with startService()
instead of the binding pattern with bindService()
. Notably, binding is a bit of a pain when it comes to dealing with configuration changes (e.g., screen rotations).
What is the best way for the Service to call the Activity? Do I use Intents, BroadcastReceivers, Messages? How?
See Notify activity from service
这篇关于与来自服务的活动 (LocalService) 通信 - Android 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!