Android ResultReceiver 汇总

来源:互联网 发布:java bug管理系统 编辑:程序博客网 时间:2024/05/21 15:40

收集的相关信息:

<1> From: http://www.eoeandroid.com/thread-325401-1-1.html

发现网络上对ResultReceiver的资料很少,刚好项目中用到,就花点时间整理下,提大家参考。

首先看下官网对 ResultReceiver的解释
Generic interface for receiving a callback result from someone. Use this by creating a subclass and implement onReceiveResult(int, android.os.Bundle), which you can then pass to others and send through IPC, and receive results they supply with send(int, android.os.Bundle).

简单翻译下:

ResultReceiver是一个用来接收他人回调结果的通用接口。要使用它,你需要创建一个子类并且实现onReceiveResult(int, android.os.Bundle)方法。
通过这个方法,你可以通过send(int, android.os.Bundle)方法实现在进程间(IPC)传递信息

举个例子,假如我们操作完一系列UI操作之后,需要写日志。这时候会开个子线程来完成这个动作
可能根据不同的UI操作,写入的日志会有所不同。下面我们通过IntentService来简单实现下这个功能(当然你还有其他方式)
首先我们有用两个按钮来模拟两个进行的请求
在主线程中,启动一个IntentService
  1. @Override
  2.         public void onClick(View v) {
  3.                 Intent intent = new Intent(this, MyIntentService.class);
  4.                 String msg = "";
  5.                 switch (v.getId()) {
  6.                 case R.id.btn_one:
  7.                         msg = "one";
  8.                         break;
  9.                 case R.id.btn_two:
  10.                         msg = "two";
  11.                         break;

  12.                 default:
  13.                         break;
  14.                 }
  15.                 intent.putExtra(MyIntentService.IN_MSG, msg);
  16.                 startService(intent);
  17.         }
复制代码

接着看下MyIntentService
  1. public class MyIntentService extends IntentService {
  2.         private Handler handler;
  3.         public final static String IN_MSG="in";
  4.         public MyIntentService() {
  5.                 super("test");
  6.                 // TODO Auto-generated constructor stub
  7.         }
  8.         public MyIntentService(Handler handler) {
  9.                 super("test");
  10.                 this.handler=handler;
  11.                 // TODO Auto-generated constructor stub
  12.         }
  13.         @Override
  14.         protected void onHandleIntent(Intent intent) {
  15.                 String msg =intent.getStringExtra(IN_MSG);
  16. //                ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("com.lwx.multhread.resultreceiver.MyResultReceiver");
  17.                 ResultReceiver receiver = new MyResultReceiver(handler);
  18.                 Bundle resultData =new Bundle();
  19.                 resultData.putString(MyResultReceiver.RESULT_KEY, msg);
  20.                 if(msg.equals("one")){
  21.                         receiver.send(MyResultReceiver.RESULT_CODE_ONE, resultData);
  22.                 }else if(msg.equals("two")){
  23.                         receiver.send(MyResultReceiver.RESULT_CODE_TWO, resultData);
  24.                 }
  25.                 
  26.         }
  27.         

复制代码

最后是MyResultReceiver
  1. public class MyResultReceiver extends ResultReceiver{
  2.         
  3.         public static final int RESULT_CODE_ONE=1;
  4.         public static final int RESULT_CODE_TWO=2;
  5.         public static final int RESULT_CODE=1;
  6.         public static final String RESULT_KEY="key";
  7.         public MyResultReceiver(Handler handler) {
  8.                 super(handler);
  9.                 // TODO Auto-generated constructor stub
  10.         }
  11.         @Override
  12.         protected void onReceiveResult(int resultCode, Bundle resultData) {
  13.                 // TODO Auto-generated method stub
  14.                 super.onReceiveResult(resultCode, resultData);
  15.                 String msg =        resultData.getString(RESULT_KEY);
  16.                 if(resultCode==RESULT_CODE_ONE){
  17.                         Log.e("MyResultReceiver", msg);
  18.                         //操作1 
  19.                 }else if(resultCode==RESULT_CODE_TWO){
  20.                         Log.e("MyResultReceiver", msg);
  21.                         //操作2
  22.                 }
  23.         }

  24. }
复制代码



到此,介绍就算结束了。
附上ResultReceiver的中文API

http://www.apihome.cn/api/android/ResultReceiver.html


<2> From: http://stackoverflow.com/questions/4510974/using-resultreceiver-in-android

  1. You need to make custom resultreceiver class extended from ResultReceiver

  2. then implements the resultreceiver interface in your activity

  3. Pass custom resultreceiver object to intentService and in intentservice just fetch the receiver object and call receiver.send() function to send anything to the calling activity in Bundle object.

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

implements the Myresultreceiver.receiver interface in you activity, create a class variable

Public MyResultReceiver mReceiver;

initialize this variable in onCreate:

mReceiver = new MyResultReceiver(new Handler());mReceiver.setReceiver(this);

Pass this mReceiver to the intentService via:

intent.putExtra("receiverTag", mReceiver);

and fetch in IntentService like:

ResultReceiver rec = intent.getParcelableExtra("receiverTag");

and send anything to activity using rec as:

Bundle b=new Bundle();rec.send(0, b);

this will be received in onReceiveResult of the activity. You can view complete code at:IntentService: Providing data back to Activity

Edit: You should call setReceiver(this) in onResume and setReceiver(null) in onPause() to avoid leaks.


<3>http://stackoverflow.com/questions/13178075/broadcast-receiver-and-resultreceiver-in-android

What is difference between BroadcastReceiver and ResultReceiver in android?


Result Receiver:

Generic interface for receiving a callback result from someone.

Broadcast Receiver:

Base class for code that will receive intents sent by sendBroadcast().

EDIT:

Background: All networking operations/long running operations should take place away from the main thread. Two ways to do this :

  1. Async task - For Simple networking like say retreive an image/ do db processing
  2. Service - For Complex long running background process

If you need to perform work outside your main thread, but only while the user is interacting with your application, then you should probably instead create a new thread and not a service. For example, if you want to play some music, but only while your activity is running, you might create an Async Thread. But if you want the process to continue even after the user exits the app (say a download) then use a service

Lets say you pick 2. Now

  1. You activity sends a web request to your service
  2. Your service executes that using say DefaultHttpClient
  3. It sends back data to your activity.

    The third step of receiving data here can be done in two ways

1.) Broadcast receiver: Multiple receivers can receive your data. Used if you want to send data/notifications across applications(say you are also interacting with fb and twitter, multiple receivers for your web broadcast), whenever you send broadcast its sent system wide.

2.) Result receiver: Your application is the only receiver of the data. It is an Interface you implement and pass it to the intentService through putExtra. IntentService will then fetch this object and call its receiver.send function to send anything (in bundle) to calling activity. Result receiver has preference over broadcast receivers if your all communication is internal to your application

EDIT: I should also mention this caution

Caution: A service runs in the main thread of its hosting process—the service does not create its own thread and does not run in a separate process (unless you specify otherwise). This means that, if your service is going to do any CPU intensive work or blocking operations (such as MP3 playback or networking), you should create a new thread within the service to do that work. By using a separate thread, you will reduce the risk of Application Not Responding (ANR) errors and the application's main thread can remain dedicated to user interaction with your activities.






0 0
原创粉丝点击