zoukankan      html  css  js  c++  java
  • Messenger实现进程间通信(IPC)

    messenger内部也是实现aidl通信,所以可以看做一个轻量级aidl,但相对比较简单.首先开启一个服务并实现一个Handler用来处理消息,在onbind方法中返回IBinder对象,通过Serviceconnect绑定服务,并把IBinder对象传递到Serviceconnect的IBinder iBinder 参数中.在onServiceConnected中创建message对象并发送带bundle的消息

    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Button button = findViewById(R.id.button);
            Intent intent = new Intent(MainActivity.this, MyService.class);
            bindService(intent,mConnection,BIND_AUTO_CREATE);
    
        }
        private ServiceConnection mConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
    
                Messenger messenger = new Messenger(iBinder);
                Message message = Message.obtain(null, 1);//获得一个message对象,并设置what标记为1
                Bundle bundle = new Bundle();
                bundle.putString("msg","msgisme");
                message.setData(bundle);
                try {
                    messenger.send(message);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
    
            @Override
            public void onServiceDisconnected(ComponentName componentName) {
    
            }
        };
    
    
    
    
    
        @Override
        protected void onDestroy() {
            unbindService(mConnection);
            super.onDestroy();
        }
    }

    上面是主activity代码

    public class MyService extends Service {
        public MyService() {
        }
    
        private static final String TAG = "yjm";
    
        private static class abchandle extends Handler {
            @Override
            public void handleMessage(Message msg) {
                if(msg.what==1){
    //                Log.e(TAG,msg.getData().getString("msg"));
                    System.out.println(msg.getData().getString("msg"));
                }
                super.handleMessage(msg);
            }
        }
    
    
        private Messenger messenger=new Messenger(new abchandle());
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return messenger.getBinder();
        }
    }

    上面是创建服务代码

  • 相关阅读:
    java数据库编程之DAO模式
    java数据库编程之JDBC
    java数据库编程之初始Mysql
    java数据库编程之常用的操作用户和赋权限
    java数据库编程之事务、视图、索引、备份、恢复
    java数据库编程之嵌套子查询及exists的使用
    .net窗体程序的基础知识及详细笔记
    sql sever 基础知识及详细笔记
    java基础知识及详细笔记
    计算机基础知识及笔记
  • 原文地址:https://www.cnblogs.com/Ocean123123/p/10956661.html
Copyright © 2011-2022 走看看