简体   繁体   English

活动处于暂停状态或处于停止状态时,服务发送到活动

[英]Service sending to activity when activity is either onPause or onStop State

Anyone know can activity received the message send by service while activity is in onStop or onPause State? 任何人都知道活动处于onStop或onPause状态时,活动可以接收到服务发送的消息吗? How should I handle so that Activity will received the message send by service while in background? 我应该如何处理,以便Activity在后台接收活动发送的消息? I have an Activity which is received locations send by service from the background. 我有一个“活动”,该活动是通过后台从服务发送位置的。 My activity is updating how much user travel every 10 seconds. 我的活动是每10秒更新一次用户旅行量。 If the activity is in onPause mode, I don't think activity can do any calculation send by service. 如果活动处于onPause模式下,我认为活动无法进行任何按服务发送的计算。

Yes and no. 是的,没有。 Your activity can't actually receive broadcasts while it's paused or stopped, but you can have your broadcast cause it to be woken back up. 您的活动在暂停或停止时实际上无法接收广播,但是您可以让广播将其唤醒。 But that's probably not something you want to do every 10 seconds. 但这可能不是您想每10秒执行一次的操作。 It would likely be better to just keep the knowledge in the service and have the activity ask for it when it gets restarted. 最好将知识保留在服务中,让活动在重新启动时要求它。 If that's an approach you're after I can point you to some examples. 如果您采用的是这种方法,我可以为您提供一些示例。

I would recommend you to do the following : 我建议您执行以下操作:

  1. Whatever computation you do, do it in the service. 无论您执行什么计算,都可以在服务中完成。 So you will always have the state of user maintained somewhere. 因此,您将始终在某处维护用户状态。

  2. When your activity starts, 'Bind' the service to the activity and call your function of the service FROM the activity to retrieve the state of the user. 当您的活动开始时,将服务“绑定”到活动,然后从活动中调用服务的功能以检索用户状态。 You can use the 'ServiceConnection' class for this in the activity. 您可以在活动中为此使用“ ServiceConnection”类。

  3. You can call your function of the service from the activity in your 'onResume' function of the activity. 您可以在活动的“ onResume”功能中从活动中调用服务的功能。

Viewable content should be in the activity and all the other data in the service. 可见内容应在活动中,服务中应包含所有其他数据。 When you do the above, the user will see the latest stuff that you want to show. 当您执行上述操作时,用户将看到您想要显示的最新内容。 There is no point in sending data to the activity and doing the computation there even if the user does not see it. 即使用户没有看到,也没有必要将数据发送到活动并在那里进行计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM