activity与service 使用Handler Messenger数据传递

service 中创建handler

 

/**
 * 用于接收从客户端传递过来的数据
 */
class IncomingHandler extends Handler {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 6:
                Log.i("map", "thanks,Service had receiver message from client!");
                break;
            default:
                super.handleMessage(msg);
        }
    }
}

/**
 * 创建Messenger并传入Handler实例对象
 */
final Messenger mMessenger = new Messenger(new IncomingHandler());
 
/**
 * 当绑定Service时,该方法被调用,将通过mMessenger返回一个实现
 * IBinder接口的实例对象
 */
@Override
public IBinder onBind(Intent intent) {
    Log.i(TAG, "Service is invoke onBind");
    return mMessenger.getBinder();
}

 

activity 中创建Messenger和ServiceConnection

 

 

/**
 * 与服务端交互的Messenger
 */
Messenger mMessenger = null;

/** Flag indicating whether we have called bind on the service. */
boolean mBound;

/**
 * 实现与服务端链接的对象
 */
private ServiceConnection mConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        /**
         * 通过服务端传递的IBinder对象,创建相应的Messenger
         * 通过该Messenger对象与服务端进行交互
         */
        mMessenger = new Messenger(service);
        mBound = true;
    }

    public void onServiceDisconnected(ComponentName className) {
        // This is called when the connection with the service has been
        // unexpectedly disconnected -- that is, its process crashed.
        mMessenger = null;
        mBound = false;
    }
};

开启service

 

bindService(new Intent(MainActivity.this, ForegroundService.class), mConnection,
        Context.BIND_AUTO_CREATE);

activity 发送数据到service

 

public void sayHello(View v) {
    if (!mBound) return;
    // 创建与服务交互的消息实体Message
    Message msg = Message.obtain(null, 6, 0, 0);
    try {
        //发送消息
        mMessenger.send(msg);
    } catch (RemoteException e) {
        e.printStackTrace();
    }
}

 

你可能感兴趣的:(移动开发)