沟通与服务(本地服务)活动 - Android的最佳实践 [英] Communicate with Activity from Service (LocalService) - Android Best Practices

查看:119
本文介绍了沟通与服务(本地服务)活动 - Android的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

常见的场景 - 活动与后台服务轮询服务器

该服务将通过AlarmManager定期运行,还为活动执行任务(用户点击一个按钮,去获取来自服务器的东西)。

我想知道这里的​​最佳实践。我认为最好的设计是Android的本地服务例如: <一href="http://developer.android.com/reference/android/app/Service.html#LocalServiceSample">http://developer.android.com/reference/android/app/Service.html#LocalServiceSample

但本例中的活动有一个参考的活动 mBoundService ,但没有反向连接(服务有没有办法来调用活动)。

什么是服务调用活动的最佳方法是什么?

难道我用的意图,BroadcastReceivers,消息?怎么样?

解决方案
  

我认为最好的设计是Android的本地服务例如:<一href="http://developer.android.com/reference/android/app/Service.html#LocalServiceSample">http://developer.android.com/reference/android/app/Service.html#LocalServiceSample

我不会。使用宽松可能的连接,你可以忍受。因此,平均而言,目的是为与命令模式startService(),而不是用的结合模式bindService()。值得注意的是,绑定是一个有点疼痛,当谈到处理的配置变化(如屏幕旋转)。

  

什么是服务调用活动的最佳方法是什么?难道我用的意图,BroadcastReceivers,消息?怎么样?

请参阅安卓通知从服务活动

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 android: notify activity from service

这篇关于沟通与服务(本地服务)活动 - Android的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆