Android Chat Application using RabbitMQ

10 May

We can create a chat application using RabbitMQ on Android. RabbitMQ is a software broker for Message-Oriented Middleware (MOM). MOM is used for asynchronous transfer of messages between different systems and platforms. You can have a look at the RabbitMQ tutorials.

There is a great tutorial available on Android and RabbitMQ on Simon Dixon’s blog. We will extend that tutorial to make a chat application (you need the code from that tutorial for this application to be working). Here we go!

We will need two fields to enter data for  name and the text message, which can be done via EditText 


final EditText etv1 = (EditText) findViewById(R.id.out3);
 etv1.setOnKeyListener(new OnKeyListener() {
 public boolean onKey(View v, int keyCode, KeyEvent event) {
 // If the event is a key-down event on the "enter" button
 if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
 (keyCode == KeyEvent.KEYCODE_ENTER)) {
 // Perform action on key press

name = etv1.getText().toString();

etv1.setText("");
 etv1.setVisibility(View.GONE);
 return true;
 }
 return false;
 }
 });

Another EditText for entering the text.


final EditText etv = (EditText) findViewById(R.id.out2);
 etv.setOnKeyListener(new OnKeyListener() {
 public boolean onKey(View v, int keyCode, KeyEvent event) {
 // If the event is a key-down event on the "enter" button
 if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
 (keyCode == KeyEvent.KEYCODE_ENTER)) {
 // Perform action on key press
 message = name + ": " + etv.getText().toString();
 new Send().execute(message);
 etv.setText("");

return true;
 }
 return false;
 }
 });

The main functionality of sending the messages or text is achieved through AysncTask, AysncTask can be used for threading and doesn’t need that much of coding. In this last EditText we call the method execute of the class Send which extends the AysncTask. For more understanding you can also refer to this article. The commands of RabbitMQ can not be executed directly we need to run the commands in a non-blocking thread. AysncTask is an easy of achieving this.

Here is the full code that you will implement (in Simon’s its the ActivityHome class):


public class ChatAppActivity extends Activity {
 private MessageConsumer mConsumer;
 private TextView mOutput;
 private String QUEUE_NAME="bye";
 private String EXCHANGE_NAME="logs";
 private String message = "";
 private String name = "";
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.main);
 Toast.makeText(ChatAppActivity.this, "RabbitMQ Chat Service!", Toast.LENGTH_LONG).show();

final EditText etv1 = (EditText) findViewById(R.id.out3);
 etv1.setOnKeyListener(new OnKeyListener() {
 public boolean onKey(View v, int keyCode, KeyEvent event) {
 // If the event is a key-down event on the "enter" button
 if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
 (keyCode == KeyEvent.KEYCODE_ENTER)) {
 // Perform action on key press
 name = etv1.getText().toString();
 etv1.setText("");
 etv1.setVisibility(View.GONE);
 return true;
 }
 return false;
 }
 });

final EditText etv = (EditText) findViewById(R.id.out2);
 etv.setOnKeyListener(new OnKeyListener() {
 public boolean onKey(View v, int keyCode, KeyEvent event) {
 // If the event is a key-down event on the "enter" button
 if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
 (keyCode == KeyEvent.KEYCODE_ENTER)) {
 // Perform action on key press
 message = name + ": " + etv.getText().toString();
 new send().execute(message);
 etv.setText("");
 return true;
 }
 return false;
 }
 });

//The output TextView we'll use to display messages
 mOutput = (TextView) findViewById(R.id.output);

//Create the consumer
 mConsumer = new MessageConsumer("141.24.xx.xxx",
 "logs",
 "fanout");

//Connect to broker
 mConsumer.connectToRabbitMQ();

//register for messages
 mConsumer.setOnReceiveMessageHandler(new OnReceiveMessageHandler(){

public void onReceiveMessage(byte[] message) {
 String text = "";
 try {
 text = new String(message, "UTF8");
 } catch (UnsupportedEncodingException e) {
 e.printStackTrace();
 }

mOutput.append("\n"+text);
 }
 });

}

private class send extends AsyncTask<String, Void, Void >{

@Override
 protected Void doInBackground(String... Message) {
 try {

ConnectionFactory factory = new ConnectionFactory();
 factory.setHost("141.24.xx.xxx");

//my internet connection is a bit restrictive so I have use an external server
// which has RabbitMQ installed on it. So I use "setUsername" and "setPassword"
factory.setUsername("XXXXX");
 factory.setPassword("xxxx");
 Connection connection = factory.newConnection();
 Channel channel = connection.createChannel();
 channel.exchangeDeclare(EXCHANGE_NAME, "fanout", true);
 channel.queueDeclare(QUEUE_NAME, false, false, false, null);
 String tempstr="";
 for(int i=0;i<Message.length;i++)
 tempstr+=Message[i];

channel.basicPublish(EXCHANGE_NAME,QUEUE_NAME, null, tempstr.getBytes());

channel.close();

connection.close();

}
 catch (Exception e) {
 // TODO: handle exception
 e.printStackTrace();
 }
 // TODO Auto-generated method stub
 return null;
 }

}

@Override
 protected void onResume() {
 super.onPause();
 mConsumer.connectToRabbitMQ();
 }

@Override
 protected void onPause() {
 super.onPause();
 mConsumer.dispose();
 }
 }

At last you modify the main.xml as following and don’t forget to include internet permission in Android Manifest:


<?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_height="wrap_content"
 android:layout_width="fill_parent">

<ScrollView
 android:layout_height="fill_parent"
 android:layout_width="fill_parent">
 <TextView
 android:id="@+id/output"
 android:layout_height="fill_parent"
 android:layout_width="wrap_content"
 />
 </ScrollView>
 <EditText
 android:id="@+id/out3"
 android:layout_height="70px"
 android:layout_width="fill_parent"
 android:layout_alignParentTop="true"
 android:maxHeight="70px"
 android:hint="Enter Name:"
 android:inputType="textVisiblePassword"
 />
 <EditText
 android:id="@+id/out2"
 android:layout_height="70px"
 android:layout_width="fill_parent"
 android:layout_alignParentBottom="true"
 android:maxHeight="70px"
 android:inputType="textVisiblePassword"
 />
 </RelativeLayout>

Here are the snapshots of chat application running on two emulators.

 

P.S. I believe all the code has been provided in this article. I don’t have the source code with me now as it got deleted, apologies for that.

Advertisements

6 Responses to “Android Chat Application using RabbitMQ”

  1. Praveena kumara D (@praveena_kd) June 10, 2012 at 8:20 am #

    Thanks a lot.. Adding a Send function was really handy for the beginners ..

    • Max Carroll August 5, 2014 at 11:04 am #

      Hi, I am doing my University project on Pub/Sub across android, Can I please have your name so I may reference this article in my report?

      PS thanks for the article, if it wasn’t for your article I wouldn’t have been able to build my pub/sub system.

      Kind Regards

      Max

      • kamrana August 6, 2014 at 5:58 am #

        It’s good to know that I am of help to you. My name is Muhammad Kamran Afridi. Also do send me your article if that is not an issue, I would like to read it as I am out of touch now a days.

      • Max Carroll August 6, 2014 at 9:51 am #

        Thanks a lot, I can give you fill credit in my references now, yes sure, It will be ready by Sunday hopefully, I can also send you the modified code, so that you can specify which group you want to be in and you only receive ,messages for that group 🙂

  2. Max August 14, 2014 at 1:40 pm #

    Hi, My project is completed, If you email me with your email, Ill send it to you

    Regards

    Max

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: