如何将数据从服务发送到活动? [英] How to send data from service to activity?

查看:192
本文介绍了如何将数据从服务发送到活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android开发的初学者。
我尝试创建一种MusicPlayer,它使用Service播放音乐。
当我在MainActivity中点击按钮时,我使用Intent调用startService,其中包括操作的信号,如播放,暂停,停止等。
但是我想从服务发回数据到活动。例如,当当前轨道停止并开始播放下一个轨道时,MainActivity得到轨道名称和作者名称。或者当播放列表中的最后一个轨道停止时,活动上的按钮暂停被改变为播放。
我需要以地图形式发送数据。喜欢title:value,playing:false。
所以,我试过。
第一个PendingIntent。我在Activity中创建它,并通过startService发送到服务。我需要在PendingIntent中指定请求代码,在Intent中为此PendingIntent指定操作。我不知道,如何使用它。
然后我试过bindService。但是Service发送数据只有当Activity请求它。
我没有找到的另一个例子。

I'm beginner in Android development. I try to create kind of MusicPlayer, which uses Service for playing music. When I click buttons in MainActivity, I call startService with Intent, which includes signal for action, such as play, pause, stop, etc... But I want to send data back from service to activity. For example, when current track has stopped and begin to play the next one, MainActivity got to receive track name and author name. Or when last track in the playlist is stopped, button "Pause" on the Activity got to changed to "Play". I need to send data as map. Like "title: value", "playing: false". So, what I tried. At first PendingIntent. I create it in the Activity and send by startService to the Service. I need to specify request code in PendingIntent, sting action in Intent for this PendingIntent. I don't know, how to use it. Then I tried bindService. But Service send data only if Activity request it. Another examples I didn't find.

从Service到Activity最简单的发送方式是什么?

Which way is most simple to send data from Service to Activity?

推荐答案

使用信使在onHandleIntent()方法从服务发送消息,然后用A处理程序接收它...参见教程 http://www.vogella.com/articles/AndroidServices/article.html

Use a messenger to send the Message from the Service on onHandleIntent() method, then Recieve it with A handler...see this tutorial http://www.vogella.com/articles/AndroidServices/article.html

这篇关于如何将数据从服务发送到活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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