如何从服务回调到活动 [英] How to make a callback from a Service to an Activity

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

问题描述

对不起,再缠着你,但我仍然无法找到一种方法,使我从一个活动回调服务...

Sorry for bugging you again, but I still can't find a way to make a callback from my activity to a service...

发现了类似的问题? - 如何在Android中定义回调

Found a similar question - How to Define Callbacks in Android?

// The callback interface
interface MyCallback {
    void callbackCall();
}

// The class that takes the callback
class Worker {
   MyCallback callback;

   void onEvent() {
      callback.callbackCall();
   }
}

// Option 1:

class Callback implements MyCallback {
   void callback() {
      // callback code goes here
   }
}

worker.callback = new Callback();

但不知道如何该样本融入我的项目。

yet not sure how to integrate that sample into my project.

任何建议或链接来清除教程将是巨大的!

Any suggestions or links to clear tutorials would be great!

推荐答案

这样的回调(Observer模式),您都出现在你的例子不会在服务和活动之​​间的合作。使用时,从A级,您创建实例B类并想送选自B回调到A观察者拍打。

That kind of callbacks (Observer pattern) that you are showing in your example won't work between a service and an activity. Use observer patter when, from class A, you created the instance of class B and want to send callbacks from B to A.

至于服务和活动,事情就完全不同了。 AFAICT,如果你要回拨你的活动服务,实现这一目标的最好方法是使用<一个HREF =htt​​p://developer.android.com/reference/android/os/ResultReceiver.html相对=nofollow> ResultReceiver 。有一个关于很多有趣的事 ResultReceiver

With regards to the services and activities, things are completely different. AFAICT, if you want to callback your Activity from a Service, the best method to achieve this is to use ResultReceiver. There are a lot of interesting things about ResultReceiver:


  • 它的构造函数接收一个 处理程序 (你必须在活动中创建),这将允许您从服务更改UI。

  • 它实现 Parcelable 因此你可以把一个参考你的 ResultReceiver 在你用来启动服务意图演员

  • 及其的onReceive 方法有一个结果code整数使您可以生成不同类型的回调(这就像如果你的回调接口有许多方法)。此外,它收到 捆绑 ,你可以用它来把所有结果数据。

  • Its constructor receives a Handler (that you must create inside the activity), which will allow you to change UI from the service.
  • It implements Parcelable thus you can put a reference of your ResultReceiver in the Intent extras that you used to start the service.
  • Its onReceive method has a result code integer which allows you to generate different kind of callbacks (this is like if your callback interface had many methods). Also, it receives a Bundle which you can use to put all result data.

在另一方面,如果你想要做一个的回调的(不知道这是在这种情况下,正确的术语),从你的活动你的服务,我想你将不得不发送广播消息或类似的东西。

On the other hand, if you want to do a callback (not sure if that is correct term in this case), from your Activity to your Service, I guess you will have to send a Broadcast message or something like that.

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

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