zoukankan      html  css  js  c++  java
  • 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();
        }
    }

     

  • 相关阅读:
    寄存器(内存访问)知识整理
    寄存器知识点
    汇编语言之实验一
    汇编语言基础知识的总结
    汇编语言之第五章至第八章知识汇总
    汇编实验之第八章数据处理的两个基本问题
    汇编语言之第七章更灵活的定位内存地址的方法
    汇编语言之实验九
    汇编语言之第六章包含多个段的程序
    汇编语言之第五章【BX】和loop指令
  • 原文地址:https://www.cnblogs.com/anni-qianqian/p/5404710.html
Copyright © 2011-2022 走看看