码迷,mamicode.com
首页 > 系统相关 > 详细

Messenger实现进程间通信(IPC)

时间:2019-05-31 18:11:53      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:intent   private   exce   ack   gets   puts   ide   send   简单   

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

上面是创建服务代码

Messenger实现进程间通信(IPC)

标签:intent   private   exce   ack   gets   puts   ide   send   简单   

原文地址:https://www.cnblogs.com/Ocean123123/p/10956661.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!