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

     

  • 相关阅读:
    泛型约束new()的使用
    控制反转-依赖注入
    微服务的六个基本点
    java反编译工具
    Idea中一些常用设置
    JSP内置对象(9个常用的内置对象)
    输出输入流,的应用

    容器集合类
    容器与集合
  • 原文地址:https://www.cnblogs.com/anni-qianqian/p/5404710.html
Copyright © 2020-2023  润新知