如何从一个服务调用一个方法,在活动 [英] How to call a method in activity from a service

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

问题描述

有监听部分的语音服务。如果声音字符串匹配一定的方法是在服务对象中调用。

There is a service that listens for some voice. If voice matches a string a certain method is invoked in the service object.

public class SpeechActivationService extends Service {

     public static Intent makeStartServiceIntent(Context pContext){    

         return new Intent(pContext, SpeechActivationService.class);
     }

     //...

     public void onMatch(){
         Log.d(TAG, "voice matches word");
     }

     //...
}

这就是我在我的活动中启动该服务:

This is how I start the service in my activity:

Intent i = SpeechActivationService.makeStartServiceIntent(this);
startService(i);

从该服务的方法,我怎么能调用驻留在活动对象的方法?我不想从活动获取服务,但是从服务的活动。我已经阅读有关处理程序和广播,但找不到/听懂的例子。任何想法?

From this service method, how can I invoke a method that resides in the activity object? I don't want access from activity to service, but from service to activity. I already read about handlers and broadcasters but could not find/understand any example. Any ideas?

推荐答案

我会登记在活动一个BroadcastReceiver,并从服务发送一个Intent给它。 看到这个教程:<一href="http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html">http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html 它可能看起来有点长,但你要学习如何使用那些反正;)

I would register a BroadcastReceiver in the Activity and send an Intent to it from the service. See this tutorial: http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html It might look a bit long but you'll want to learn how to use those anyway ;)

这篇关于如何从一个服务调用一个方法,在活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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