}
}
});
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mServerMessenger.getBinder();
}
}
public class ClientActivity extends Activity {
private TextView mNameTxt;
/**
- 客户端Messenger对象,用来接收服务端数据
*/
private Messenger mClientMessenger = new Messenger(new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1000:
// 接收服务端数据
Bundle bundle = (Bundle) msg.obj;
mNameTxt.setText(bundle.getString(“name”));
break;
}
}
});
/**
- 服务端Messenger对象,建立连接时获取,用来给服务端发消息
*/
private Messenger mServerMessenger;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 获取服务端Messenger对象
mServerMessenger = new Messenger(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
mServerMessenger = null;
}
};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_common);
mNameTxt = (TextView) findViewById(R.id.name);
// 绑定远端服务
Intent intent = new Intent(this, MsgerService.class);
bindService(intent, mConnection, BIND_AUTO_CREATE);
findViewById(R.id.bind).setOnClickList