android - 如何从服务调用 Activity 中的方法

标签 android android-intent android-service android-handler

有一个服务可以监听一些声音。如果语音与字符串匹配,则会在服务对象中调用某个方法。

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");
     }

     //...
}

这是我在我的 Activity 中启动服务的方式:

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

如何从这个服务方法调用驻留在 Activity 对象中的方法?我不想从 Activity 访问到服务,而是从服务到 Activity 。我已经阅读了有关处理程序和广播者的信息,但找不到/理解任何示例。有什么想法吗?

最佳答案

假设您的 Service 和 Activity 在同一个包中(即同一个应用程序),您可以按如下方式使用 LocalBroadcastManager:

在您的服务中:

// Send an Intent with an action named "my-event". 
private void sendMessage() {
  Intent intent = new Intent("my-event");
  // add data
  intent.putExtra("message", "data");
  LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

在您的 Activity 中:

@Override
public void onResume() {
  super.onResume();

  // Register mMessageReceiver to receive messages.
  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
      new IntentFilter("my-event"));
}

// handler for received Intents for the "my-event" event 
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    // Extract data included in the Intent
    String message = intent.getStringExtra("message");
    Log.d("receiver", "Got message: " + message);
  }
};

@Override
protected void onPause() {
  // Unregister since the activity is not visible
  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
  super.onPause();
}

来自@Ascorbin 链接的第 7.3 节:http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html#ownreceiver_localbroadcastmanager

关于android - 如何从服务调用 Activity 中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14896574/

相关文章:

Android:创建文件时出现问题

android - SecurityException : Not allowed to start service Intent act=com. google.android.c2dm.intent.REGISTER

android - 你如何实现 DaggerService

android - 升级的Android Studio-项目不再构建gradle构建工具版本

android - 如何让 Flutter Workmanager 插件和 Location 插件一起工作

android - 控制 MDM/MAM 受控设备的用户可以下载哪些应用程序

java - 如何在 Activity 重新启动时保留 Intent 对象的值?

android - 在 FrameLayout 中启动 Activity

android - 是否可以连接到 Spotify 的 MediaBrowserService?

android - 为什么在应用程序进程中使用绑定(bind)(未启动)服务?