问题描述
从根本上说,我想建立一个从 IntentService 到 Activity 的回调.我的问题与此处回答的问题非常相似:
Fundamentally, I would like to establish a callback to an Activity from an IntentService. My question is very similar to the one answered here:
然而,在应答代码中,活动代码被视为实现了一个 ResultReceiver.除非我遗漏了什么,否则 ResultReceiver 实际上是一个类,因此它无法执行此实现.
However, in the answer code, the activity code is seen as implementing a ResultReceiver. Unless I'm missing something, ResultReceiver is actually a class, so it cannot perform this implementation.
所以本质上,我问的是将 ResultReceiver 连接到该服务的正确方法是什么.在这方面,我对 Handler 和 ResultReceiver 概念感到困惑.任何工作示例代码将不胜感激.
So essentially, I'm asking what would be the correct way to wire up a ResultReceiver to that service. I get confused with Handler and ResultReceiver concepts with respect to this. Any working sample code would be appreciated.
推荐答案
您需要使自定义 resultreceiver 类从结果接收者
You need to make custom resultreceiver class extended fromResultReceiver
然后在您的活动中实现 resultreceiver 接口
then implements the resultreceiver interface in your activity
将自定义的 resultreceiver 对象传递给 intentService 并传入intentservice 只是获取接收者对象并调用receiver.send() 函数将任何内容发送到调用活动捆绑对象.
Pass custom resultreceiver object to intentService and inintentservice just fetch the receiver object and callreceiver.send() function to send anything to the calling activity inBundle object.
这里是 customResultReceiver 类:
here is customResultReceiver class :
public class MyResultReceiver extends ResultReceiver {
private Receiver mReceiver;
public MyResultReceiver(Handler handler) {
super(handler);
// TODO Auto-generated constructor stub
}
public interface Receiver {
public void onReceiveResult(int resultCode, Bundle resultData);
}
public void setReceiver(Receiver receiver) {
mReceiver = receiver;
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (mReceiver != null) {
mReceiver.onReceiveResult(resultCode, resultData);
}
}
}
在你的Activity中实现Myresultreceiver.receiver接口,创建一个类变量
implements the Myresultreceiver.receiver interface in you activity, create a class variable
Public MyResultReceiver mReceiver;
在 onCreate 中初始化这个变量:
initialize this variable in onCreate:
mReceiver = new MyResultReceiver(new Handler());
mReceiver.setReceiver(this);
通过以下方式将此 mReceiver 传递给 intentService:
Pass this mReceiver to the intentService via:
intent.putExtra("receiverTag", mReceiver);
并在 IntentService 中获取,例如:
and fetch in IntentService like:
ResultReceiver rec = intent.getParcelableExtra("receiverTag");
并使用 rec 将任何内容发送到活动:
and send anything to activity using rec as:
Bundle b=new Bundle();
rec.send(0, b);
这将在活动的 onReceiveResult 中接收.您可以在以下位置查看完整代码:IntentService:向 Activity 提供数据
this will be received in onReceiveResult of the activity. You can view complete code at:IntentService: Providing data back to Activity
您应该在 onResume 中调用 setReceiver(this) 并在 onPause() 中调用 setReceiver(null) 以避免泄漏.
这篇关于在 Android 中使用 ResultReceiver的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!