basic4android 推送,Android接收RabbitMQ消息。

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

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值