packagecom.ldb.longdb.rabbitmqapp;importandroid.os.Bundle;importandroid.os.Handler;importandroid.os.Message;importandroid.support.v7.app.AppCompatActivity;importandroid.util.Log;importandroid.widget.TextView;importcom.rabbitmq.client.AMQP;importcom.rabbitmq.client.Channel;importcom.rabbitmq.client.Connection;importcom.rabbitmq.client.ConnectionFactory;importcom.rabbitmq.client.DefaultConsumer;importcom.rabbitmq.client.Envelope;importjava.io.IOException;importjava.util.concurrent.TimeoutException;public class MainActivity extendsAppCompatActivity {
ConnectionFactory factory;
@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);//连接设置
setupConnectionFactory();//用于从线程中获取数据,更新ui
final Handler incomingMessageHandler = newHandler() {
@Overridepublic voidhandleMessage(Message msg) {
String message= msg.getData().getString("msg");
TextView tv=(TextView) findViewById(R.id.txtrabbitmqt);
tv.append(message+ '\n');
Log.i("test", "msg:" +message);
}
};//开启消费者线程//subscribe(incomingMessageHandler);
new Thread(newRunnable() {
@Overridepublic voidrun() {
basicConsume(incomingMessageHandler);
}
}).start();
}/*** 连接设置*/
private voidsetupConnectionFactory() {
factory= newConnectionFactory();
factory.setHost(服务器ip);
factory.setPort(5672);
factory.setUsername("longdb");
factory.setPassword("***");
}/*** 收消息(从发布者那边订阅消息)*/
private void basicConsume(finalHandler handler){try{//连接
Connection connection =factory.newConnection() ;//通道
final Channel channel =connection.createChannel() ;//实现Consumer的最简单方法是将便捷类DefaultConsumer子类化。可以在basicConsume 调用上传递此子类的对象以设置订阅:
channel.basicConsume("myqueue" , false , newDefaultConsumer(channel){
@Overridepublic void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throwsIOException {super.handleDelivery(consumerTag, envelope, properties, body);
String msg= newString(body) ;long deliveryTag =envelope.getDeliveryTag() ;
channel.basicAck(deliveryTag ,false);//从message池中获取msg对象更高效
Message uimsg =handler.obtainMessage();
Bundle bundle= newBundle();
bundle.putString("msg", msg);
uimsg.setData(bundle);
handler.sendMessage(uimsg);
}
});
}catch(IOException e) {
e.printStackTrace();
}catch(TimeoutException e) {
e.printStackTrace();
}
}
}