Messenger信使

* Messenger用于Activity和Service之间消息传递

需求:activity来绑定服务,绑定成功后,将数据发送给service,service收到消息后,再发送信息给activity.

public class MainActivity extends AppCompatActivity {
    private Intent intent;
    private MyServiceConnection serviceConnection;
    private Messenger messenger;//信使。
    private Messenger activity_messenger;//
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
          String str = (String) msg.obj;
            System.out.println(str);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        activity_messenger = new Messenger(handler);
        //绑定服务。
        intent = new Intent(this,MyService.class);
        serviceConnection = new MyServiceConnection();
        bindService(intent, serviceConnection,BIND_AUTO_CREATE);
    }
    public void click(View view){
        if(messenger!=null){
            Message msg = new Message();
            msg.obj = "我是activity发送过来的消息";
            msg.replyTo =activity_messenger;
            try {
                messenger.send(msg);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }
    class MyServiceConnection implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //得到信使。service的信使.
            messenger = new Messenger(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
}
public class MyService extends Service {
   private Handler handler = new Handler(){
       @Override
       public void handleMessage(Message msg) {
         String str = (String) msg.obj;
           System.out.println(str);
           //发送消息。
          Messenger activity_messenger =  msg.replyTo;
           Message message = new Message();
           message.obj="我是service发送过来的消息";
           try {
               activity_messenger.send(message);
           } catch (RemoteException e) {
               e.printStackTrace();
           }
       }
   };
    @Override
    public IBinder onBind(Intent intent) {
        Messenger messenger = new Messenger(handler);
        return messenger.getBinder();
    }
}

 

posted @ 2016-04-18 15:37  嘉禾世兴  阅读(223)  评论(0编辑  收藏  举报