从根本上讲,我想从IntentService建立对Activity的回调。我的问题与此处回答的问题非常相似:

Restful API service

但是,在答案代码中, Activity 代码被视为实现了ResultReceiver。除非我缺少任何内容,否则ResultReceiver实际上是一个类,因此它无法执行此实现。

所以从本质上讲,我在问将ResultReceiver连接到该服务的正确方法是什么。关于这一点,我对Handler和ResultReceiver概念感到困惑。任何有效的示例代码将不胜感激。

最佳答案

  • 您需要使自定义的resultreceiver类扩展为
    ResultReceiver
  • 然后在您的 Activity
  • 中实现resultreceiver接口(interface)
  • 将自定义resultreceiver对象传递给intentService和
    intentservice只是获取接收者对象并调用
    receiver.send()函数可将任何内容发送到
    bundle 对象。

    这是customResultReceiver类:
     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接口(interface),创建一个类变量
    Public MyResultReceiver mReceiver;
    

    在onCreate中初始化此变量:
    mReceiver = new MyResultReceiver(new Handler());
    
    mReceiver.setReceiver(this);
    

    通过以下方式将此mReceiver传递给intentService:
    intent.putExtra("receiverTag", mReceiver);
    

    并在IntentService中获取,例如:
    ResultReceiver rec = intent.getParcelableExtra("receiverTag");
    

    并使用rec将任何内容发送到 Activity :
    Bundle b=new Bundle();
    rec.send(0, b);
    

    这将在 Activity 的onReceiveResult中接收。您可以在以下位置查看完整的代码:IntentService: Providing data back to Activity

    编辑:您应该在onResume中调用setReceiver(this),在onPause()中调用setReceiver(null)以避免泄漏。

    07-28 12:10