Android--Android receives RabbitMQ messages

Reference: https://blog.csdn.net/qq_36576738/article/details/83754621

I do not implement the function of posting messages on the android side. Because I am pushing messages on the server side.

Development tool android studio.

1》 Add the package after building the project (currently the latest is 5.7.0):

dependencies {
    implementation 'com.rabbitmq:amqp-client:5.7.0'
}

2》 Add a TextView on the main page to display the messages pushed by the server.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtrabbitmqt"
        android:text="rabbitmq"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

3》 Connect to RabbitMq on the server:

   / ** 
     * Connection settings 
     * / 
    private void setupConnectionFactory () { 
        factory = new ConnectionFactory (); 
        factory.setHost ("server ip"); 
        factory.setPort (rabbitmq port, default 5672); 
        factory.setUsername ("connect rabbitmq yourself Account "); 
        factory.setPassword (" Password to connect to rabbitmq yourself "); 
    }

 

4》 Write the subscription code:

    / ** 
     * Receive message (subscribe message from publisher) 
     * / 
    private void basicConsume (final Handler handler) { 

        try { 
            // Connection 
            Connection connection = factory.newConnection (); 
            // channel 
            final Channel channel = connection.createChannel (); 
            // The easiest way to implement Consumer is to subclass the convenience class DefaultConsumer. You can pass an object of this subclass on the basicConsume call to set the subscription: 
            channel.basicConsume ("myqueue", false, new DefaultConsumer (channel) { 
                @Override 
                public void handleDelivery (String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte [ ] body) throws IOException { 
                    super.handleDelivery (consumerTag, envelope, properties, body); 

                    String msg = new String (body);
                    long deliveryTag = envelope.getDeliveryTag() ;
                    channel.basicAck(deliveryTag , false);
                    //从message池中获取msg对象更高效
                    Message uimsg = handler.obtainMessage();
                    Bundle bundle = new Bundle();
                    bundle.putString("msg", msg);
                    uimsg.setData(bundle);
                    handler.sendMessage(uimsg);

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace (); 
        } 
    }

The entire demo code:

package com.ldb.longdb.rabbitmqapp;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.TextView;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class MainActivity extends AppCompatActivity {

    ConnectionFactory factory;
    @Override
    protected void onCreate (Bundle savedInstanceState) { 
        super.onCreate (savedInstanceState); 
        setContentView (R.layout.activity_main); 

        // Connection setting 
        setupConnectionFactory (); 
        // Used to get data from the thread, update ui 
        final Handler incomingMessageHandler = new Handler () { 
            @Override 
            public void handleMessage (Message msg) { 
                String message = msg.getData (). GetString ("msg"); 
                TextView tv = (TextView) findViewById (R.id.txtrabbitmqt); 
                tv.append (message + '\ n'); 
                Log.i ("test", "msg:" + message); 
            }
        };
        // Start consumer thread 
        // subscribe (incomingMessageHandler); 
        new Thread (new Runnable () { 
            @Override 
            public void run () { 
                basicConsume (incomingMessageHandler); 
            } 
        }). Start (); 
    } 

    / ** 
     * Connection settings 
     * / 
    private void setupConnectionFactory () { 
        factory = new ConnectionFactory (); 
        factory.setHost (server ip); 
        factory.setPort (5672); 
        factory.setUsername ("longdb"); 
        factory.setPassword ("***"); 
    } 

    / ** 
     * Receive message ( Subscribe to messages from the publisher) 
     * / 
    private void basicConsume (final Handler handler) {

        try { 
            // Connection 
            Connection connection = factory.newConnection (); 
            // channel 
            final Channel channel = connection.createChannel (); 
            // The easiest way to implement Consumer is to subclass convenience class DefaultConsumer. You can pass an object of this subclass on the basicConsume call to set the subscription: 
            channel.basicConsume ("myqueue", false, new DefaultConsumer (channel) { 
                @Override 
                public void handleDelivery (String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte [ ] body) throws IOException { 
                    super.handleDelivery (consumerTag, envelope, properties, body); 

                    String msg = new String (body); 
                    long deliveryTag = envelope.getDeliveryTag (); 
                    channel.basicAck (deliveryTag, false); 
                    // It is more efficient to get the msg object from the message pool 
                    Message uimsg = handler.obtainMessage ();
                    Bundle bundle = new Bundle();
                    bundle.putString("msg", msg);
                    uimsg.setData(bundle);
                    handler.sendMessage(uimsg);

                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}

View Code

I packaged it directly, and then installed and tested it on my phone.

Test steps: 1》 app opens

                  2》 springcloud service (how springspring publishes messages, please see the previous article ) runs and sends requests.

Test screenshot:

Reprinted at: https://www.cnblogs.com/longdb/p/10893413.html

Published 7 original articles · 69 praises · 200,000+ views

Guess you like

Origin blog.csdn.net/u014320421/article/details/105217793