在Android上使用活动和服务之间的同步和异步通信 [英] using synchronous and async communication between Activity and Service on Android

查看:363
本文介绍了在Android上使用活动和服务之间的同步和异步通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在写一个应用程序,它由一个服务和活动。该服务在后台运行,做一些现场音频处理。如果用户想获得正在运行的服务的一些信息,或者想改变服务的设置,活动得到启动并绑定到该服务。

I am currently writing an app, which consists of a service and an activity. The service is running in the background, doing some live audio processing. If the user want to get some information about the running service or want to change the settings of the service, the activity gets started and bind to the service.

目前我使用的是异步信使系统服务和活动之​​间进行通信。例如,该服务可以通过消息发送一些结果的活性和活性可以处理该消息,并显示该结果。这工作得很好,但它是紧张写短信东西每个通信。并且它不总是需要的。有时候,我只想问服务时,如果设置一个标志或没有。如果我为此异步的,我必须发送一个消息到其要求的标志的值与该服务有然后将消息发送回活动来回答该请求的服务。

Currently i am using the asynchronous messenger system to communicate between the service and the activity. For example, the service can send some results to the activity through a message and the activity can handle this message and show the results. This works fine, but it is stressful to write the messaging stuff for each communication. And it is not always needed. Sometimes i only want to ask the service, if a flag is set or not. If i do this asynchronous, i have to send a message to the service which asks for the value of the flag and the service has then to send a message back to the activity to answer the request.

所以我想有一些getter和setter,可以同步访问该服务。这可以通过使用一种粘合剂,其工作方式也进行。

So i want to have some getter and setter which can synchronously access the service. This can be done by using a binder, which works too.

问题是,我有时需要同步通信获得标志等的价值,有时我需要异步通信从服务到活动推动的结果。所以,我需要的是一个粘合剂和使者。但我不知道如何可以做到这一点,因为该服务只能从onBind()方法,无论是粘合剂对象或对象使者返回一个对象。

The problem is, that i sometimes need synchronous communication to get the value of flags etc. and sometimes i need asynchronous communication to push the results from the service to the activity. So what i need is a binder and a messenger. But i dont know how this can be done, because the service can only return one object from the onBind() method, either a binder object or a messenger object.

你有怎样可以做到这一点有任何建议或一些其他的方法来实现的活动和服务之间同步和异步通信?

Do you have any suggestions how this can be done or some other approach to realise asynchronous and synchronous communication between an activity and a service?

在此先感谢!

托比亚斯

推荐答案

如果您已经绑定到该服务,你的活动可以提供一个监听对象的服务,在事件发生时该服务将然后调用。

If you are already binding to the service, your activity can supply a listener object to the service, which the service will then call when events occur.

您只需要确保您注销侦听器对象之前,从服务解除绑定,并做两个活动被破坏之前,所以你的服务不具有较强的参照倒闭活动拉闸。

You just need to make sure that you unregister that listener object before unbinding from the service, and do both before the activity is destroyed, so your service does not wind up with a strong reference to a defunct activity.

这篇关于在Android上使用活动和服务之间的同步和异步通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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