Android IPC 메커니즘 (2) Messenger IPC 구현

 
  

Messenger

Messenger的底层是通过AIDL实现的,我们可以通过他的构造函数了解,如下

public Messenger(Handler target) {
    mTarget = target.getIMessenger();
}
public Messenger(IBinder target) {
    mTarget = IMessenger.Stub.asInterface(target);
}

구체적인 코드 구현
서비스 단말기
public class MessengerService extends Service {

    private static final String TAG="MessengerService";

    private static class MessengerHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case Constants.MSG_FROM_CLIENT:
                    //        
                    Log.e(TAG,"       :"+msg.getData().get("msg"));

                    //      messenger,         
                    Messenger client=msg.replyTo;
                    Message message=Message.obtain(null,Constants.MSG_FROM_SERVICE);
                    Bundle data=new Bundle();
                    data.putString("msg","     ");
                    message.setData(data);
                    try {
                        client.send(message);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;

                default:
                    super.handleMessage(msg);

            }

        }
    }

    private final Messenger mMessenger=new Messenger(new MessengerHandler());

    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();

    }
}

클라이언트
public class MessengerActivity extends AppCompatActivity {
    private static final String TAG="MessengerActivity";
    private EditText mEditText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_messenger);
        mEditText=findViewById(R.id.edt_id);
        Intent intent=new Intent(this,MessengerService.class);
        bindService(intent, mServiceConnection,Context.BIND_AUTO_CREATE);

    }

    /**
     *    Messenger
     */
    private final Messenger mGetResult =new Messenger(new Handler(){
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case Constants.MSG_FROM_SERVICE:

                    Log.e(TAG,"         :"+msg.getData().get("msg"));

                    break;
                    default:
                        super.handleMessage(msg);
            }

        }
    });
    private Messenger mService ;//    Messenger
    private ServiceConnection mServiceConnection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService=new Messenger(service);//             Messenger
            Message message=Message.obtain(null, Constants.MSG_FROM_CLIENT);
            Bundle bundle=new Bundle();
            bundle.putString("msg",mEditText.getText().toString().trim());
            message.setData(bundle);
            message.replyTo=mGetResult;
            try {
                mService.send(message);//        
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };


    /**
     *         
     * @param view
     */
    public void sendMsg(View view) {
        Message message=Message.obtain(null, Constants.MSG_FROM_CLIENT);
        Bundle bundle=new Bundle();
        bundle.putString("msg",mEditText.getText().toString().trim());
        message.setData(bundle);
        message.replyTo=mGetResult;
        try {
            mService.send(message);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        unbindService(mServiceConnection);//activity      
        super.onDestroy();
    }
}

Manifest에서 다중 프로세스를 구현하도록 구성하는 장면



그러나 주의해야 할 것은 프로세스 간 통신을 할 때 Messenger는 메시지를 통해 전달되고 메시지가 사용할 수 있는 것은 what,arg1을 포함한다.
arg2, Bundle 및 replyTo, 그리고 object도 Parcelable를 실현한 시스템 대상만 전달할 수 있습니다.

좋은 웹페이지 즐겨찾기