×
Community Blog Reliable and Fast Messaging and Notification Services for Android

Reliable and Fast Messaging and Notification Services for Android

In this tutorial, we will show the capability of the Alibaba Cloud Message Service for messaging and notification services (MNS) with Android Studio 3.

15NewTechTrendsin2017_AIBeingaTipoftheIceberg

By Sai Sarath Chandra Alibaba Cloud Tech Share Author and Alibaba Cloud MVP

This is a sample project created to demonstrate the usage of Alibaba Cloud Message Service on Android. This application shows the capability of the Message Service for messaging and notification services (MNS). You can find the repo of this project on my GitHub page.

Prerequisites:

  1. You need an Alibaba Cloud Account. If you need one, you can get one with $300 by signing up here.
  2. You'll need Android Studio 3.0.0 to build the Android app.

Steps:

1.Activate the Alibaba Cloud Message Service & get the access keys from your Alibaba Cloud Console.
2.Create Queue and get the endpoint. Follow this link for an illustrative guide.
3.Create a new Android project with Android Studio 3.0.0.

01

4.Select your required values. I am targeting API 19 and above.

02

5.Select the appropriate activity. I am choosing empty activity

03

6.Create the class, give an appropriate class name, and create the appropriate activity.xml too. I am using MainActivity.

04

7.Fill the XML details in below and copy it in the strings.xml.

<resources>
    <string name="app_name">Notification Demo</string>

    <!-- Alibaba MNS Service details-->
    <!-- Please replace this details with your own-->
    <!--Public Endpoint-->
    <string name="Endpoint">UPDATE YOUR ENDPOINT FOR QUEUES HERE</string>
    <!-- Access ID -->
    <string name="AccessKey">UPDATE YOUR ACCESS ID</string>
    <!-- Access key Secret -->
    <string name="AccessKeySecret">UPDATE YOUR ACCESS KEY HERE</string>
    <!-- Queue Names -->
    <string name="QueueName_1">-QUEUE 1 FOR SEND AND RECEIVE MESSAGE</string>
    <string name="QueueName_2">QUEUE 2 FOR NOTIFICATIONS</string>

</resources>

8.Then, switch your project view to Project in your Android Studio as shown below:

05

9.Go to the libs subfolder located under app folder, and copy the two libraries – aliyun-sdk-mns-1.1.18.jar & Jaxb-api.2.2.12.jar. Right click the libs folder and you will see the option "Add to Library".

06

10.Go to your app build.gradle file then copy the below

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        // your Pacakge Name
        applicationId "sample.alibabacloud.notificationdemo"
        // your min sdk version
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    // make sure to include this for your jars compilation
    packagingOptions {

        exclude 'META-INF/DEPENDENCIES'
    }
    useLibrary 'org.apache.http.legacy'
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile 'com.android.support:design:26.1.0'
    // Make sure you download dependency for multidex
    compile 'com.android.support:multidex:1.0.2'
    implementation files('libs/aliyun-sdk-mns-1.1.8.jar')
    implementation files('libs/jaxb-api-2.2.12.jar')
}

11.Enable multidex in your custom application class. Then, add this application class to AndroidManifest.xml

package sample.alibabacloud.notificationdemo;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.support.multidex.MultiDex;

/**
 * Created by Sarath Chandra
 */

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        startService(new Intent(this,ReceiveService.class));
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}

12.Then enable the application to access the internet by adding "uses-permission" outside application tag but inside manifest.
<uses-permission android:name="android.permission.INTERNET" />

and then copy paste the below after your activity tag

<service android:name=".ReceiveService" />

<receiver android:name=".MessageReceiver">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

13.Now, we have to create the service for our application, which receives notification, broadcast receiver, UI, and logic for sending, receiving, and sending notifications. 13. Let's create the UI copy the below code to your activity_main.xml.

<?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:id="@+id/coordinatorLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="sample.alibabacloud.notificationdemo.MainActivity">


    <Button
        android:id="@+id/sendButton"
        android:layout_width="235dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:text="Send Messages"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/receiveButton"
        android:layout_width="235dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Receive Messages"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/sendButton" />

    <Button
        android:id="@+id/sendNotification"
        android:layout_width="235dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="Send Notification"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/receiveButton" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent">

        <TextView
            android:id="@+id/opText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:textSize="16dp"
            android:layout_marginStart="8dp"
            android:text="Perform some operation for Output" />

    </ScrollView>



</android.support.constraint.ConstraintLayout>

14.Copy the below code and add it to your MainActivity.java

package sample.alibabacloud.notificationdemo;

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.ClientException;
import com.aliyun.mns.common.ServiceException;
import com.aliyun.mns.model.Message;

import java.util.Calendar;

/**
 * Created by Sarath Chandra
 */

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";
    private static String ntfcnTxt = "";
    ConstraintLayout coordinatorLayout;
    MNSClient client, client2;
    TextView opText;
    ReceiveService mBoundService;
    boolean mIsBound = true;
    CloudAccount account, account2;
    Handler handler = new Handler();
    ProgressDialog progressDialog;


    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "onServiceConnected: Connected");
            mBoundService = ((ReceiveService.LocalBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "onServiceDisconnected: Not Connected");
            mBoundService = null;
        }

    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        coordinatorLayout = findViewById(R.id.coordinatorLayout);
        opText = findViewById(R.id.opText);
        progressDialog = new ProgressDialog(this);
        initClient();


        Button sendButton = findViewById(R.id.sendButton);
        Button receiveButton = findViewById(R.id.receiveButton);
        Button sendNotification = findViewById(R.id.sendNotification);

        sendButton.setOnClickListener(this);
        receiveButton.setOnClickListener(this);
        sendNotification.setOnClickListener(this);

        startRepeatingTimer();
    }

    private void initClient() {

        account = new CloudAccount(getString(R.string.AccessKey), getString(R.string.AccessKeySecret), "http://5465505358903400.mns.ap-southeast-1.aliyuncs.com");
        account2 = new CloudAccount(getString(R.string.AccessKey), getString(R.string.AccessKeySecret), "http://5465505358903400.mns.ap-southeast-3.aliyuncs.com");
        client = account.getMNSClient();
        client2 = account2.getMNSClient();

        Log.d(TAG, "initClient: acct is open" + client.isOpen());

    }

    @Override
    public void onClick(View view) {

        int id = view.getId();

        if (id == R.id.sendButton) {
            Log.d(TAG, "onClick: Send Btn Clicked");
            progressDialog.show();
            Thread newThread = new Thread(new SendMessageTask());
            newThread.start();
        } else if (id == R.id.receiveButton) {
            Log.d(TAG, "onClick: Receive Btn Clicked");
            progressDialog.show();
            Thread newThread = new Thread(new ReceiveMessageTask());
            newThread.start();
        } else if (id == R.id.sendNotification) {
            Log.d(TAG, "onClick: Subscribing to the Topic msg to Topic");
//            progressDialog.show();


            // get prompts.xml view
            LayoutInflater li = LayoutInflater.from(this);
            View promptsView = li.inflate(R.layout.inputdialog, null);

            AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                    this);

            // set prompts.xml to alertdialog builder
            alertDialogBuilder.setView(promptsView);

            final EditText userInput = (EditText) promptsView
                    .findViewById(R.id.editTextDialogUserInput);

            // set dialog message
            alertDialogBuilder
                    .setCancelable(false)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    // get user input and set it to result
                                    // edit text
                                    ntfcnTxt = userInput.getText().toString();
                                    Thread newThread = new Thread(new SendNotificationTask());
                                    newThread.start();
                                }
                            })
                    .setNegativeButton("Cancel",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            });

            // create alert dialog
            AlertDialog alertDialog = alertDialogBuilder.create();

            // show it
            alertDialog.show();
        }

    }

    private void startRepeatingTimer() {
        Log.d(TAG, "startRepeatingTimer: start Repeating Timer");
        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(MainActivity.this, ReceiveService.class);
        PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
        if (am != null) {
            am.setRepeating(AlarmManager.RTC_WAKEUP, Calendar.getInstance().getTimeInMillis(), System.currentTimeMillis() + (1000 * 60 * 5), pi);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG, "onClick: Starting the Service");
        doBindService();
    }

    private void doBindService() {
        Log.d(TAG, "doBindService: ");
        bindService(new Intent(this, ReceiveService.class), mConnection, Context.BIND_AUTO_CREATE);
        Log.d(TAG, "doBindService: bindService Called");
        mIsBound = true;
        if (mBoundService != null) {
            Log.d(TAG, "doBindService: is Boundable");
            mBoundService.isBoundable();
        }


    }

    private void doUnbindService() {
        if (mIsBound) {
            unbindService(mConnection);
            mIsBound = false;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        doUnbindService();
    }


    class SendMessageTask implements Runnable {
        private static final String TAG = "MainAct.SndMessTask";


        StringBuilder msgsRcvd = new StringBuilder();

        @Override
        public void run() {
            CloudAccount account2 = new CloudAccount(getApplicationContext().getString(R.string.AccessKey), getApplicationContext().getString(R.string.AccessKeySecret), getApplicationContext().getString(R.string.Endpoint));
            MNSClient client2 = account2.getMNSClient();

            try {
                Log.d(TAG, "doInBackground: inside try");
                CloudQueue queue = client2.getQueueRef(getApplicationContext().getString(R.string.QueueName_1));// replace with your queue name
                for (int i = 0; i < 10; i++) {
                    Log.d(TAG, "doInBackground: inside for loop :: " + i + 1);
                    final int k = i + 1;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.setMessage("Sending Message : " + (k + 1));
                        }
                    });

                    Message message = new Message();
                    message.setMessageBody("This is message" + i);
                    Message putMsg = queue.putMessage(message);
                    Log.d(TAG, "Send message id is: " + putMsg.getMessageId());
                }

                handler.post(new Runnable() {
                    public void run() {
                        opText.setText("All Messages Sent.");
                        progressDialog.dismiss();
                    }
                });
            } catch (ClientException ce) {
                Log.d(TAG, "sendButton: Something wrong with the network connection between client and MNS service.Please check your network and DNS availablity.");
                ce.printStackTrace();
            } catch (ServiceException se) {
                if (se.getErrorCode().equals("QueueNotExist")) {
                    Log.d(TAG, "sendButton: Queue is not exist.Please create before use");
                } else if (se.getErrorCode().equals("TimeExpired")) {
                    Log.d(TAG, "sendButton: The request is time expired. Please check your local machine timeclock");
                }
                se.printStackTrace();
            } catch (Exception e) {
                Log.d(TAG, "sendButton: Unknown exception happened!");
                e.printStackTrace();
            }

        }
    }

    class ReceiveMessageTask implements Runnable {
        private static final String TAG = "MainAct.SndMessTask";

        @Override
        public void run() {
            CloudAccount account2 = new CloudAccount(getApplicationContext().getString(R.string.AccessKey), getApplicationContext().getString(R.string.AccessKeySecret), getApplicationContext().getString(R.string.Endpoint));
            final StringBuilder outputMsg = new StringBuilder();

            MNSClient client2 = account2.getMNSClient();
            try {
                Log.d(TAG, "doInBackground: inside try");
                CloudQueue queue = client2.getQueueRef(getApplicationContext().getString(R.string.QueueName_1));
                for (int i = 0; i < 10; i++) {
                    Message popMsg = queue.popMessage();
                    if (popMsg != null) {
                        Log.d(TAG, "doInBackground: message handle: " + popMsg.getReceiptHandle());
                        Log.d(TAG, "doInBackground: message body: " + popMsg.getMessageBodyAsString());
                        Log.d(TAG, "doInBackground: message id: " + popMsg.getMessageId());
                        Log.d(TAG, "doInBackground: message dequeue count:" + popMsg.getDequeueCount());


                        final int k = i + 1;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressDialog.setMessage("Receive Message " + k);
                            }
                        });


                        outputMsg.append(popMsg.getMessageBodyAsString()).append(".\n");
                        Log.d(TAG, "doInBackground: msg Received" + popMsg.getMessageBodyAsString());


                        queue.deleteMessage(popMsg.getReceiptHandle());

                        Log.d(TAG, "doInBackground: delete message successfully");
                    } else {
                        Log.d(TAG, "doInBackground: No message");

                    }

                }

                handler.post(new Runnable() {
                    public void run() {
                        opText.setText("Messages Received :\n" + outputMsg);
                        progressDialog.dismiss();
                    }
                });
            } catch (ClientException ce) {
                Log.d(TAG, "sendButton: Something wrong with the network connection between client and MNS service.Please check your network and DNS availablity.");
                ce.printStackTrace();
            } catch (ServiceException se) {
                if (se.getErrorCode().equals("QueueNotExist")) {
                    Log.d(TAG, "sendButton: Queue is not exist.Please create before use");
                } else if (se.getErrorCode().equals("TimeExpired")) {
                    Log.d(TAG, "sendButton: The request is time expired. Please check your local machine timeclock");
                }
            /*
            you can get more MNS service error code from following link:
            https://help.aliyun.com/document_detail/mns/api_reference/error_code/error_code.html?spm=5176.docmns/api_reference/error_code/error_response
            */
                se.printStackTrace();
            } catch (Exception e) {
                Log.d(TAG, "sendButton: Unknown exception happened!");
                e.printStackTrace();
            }

        }
    }

    class SendNotificationTask implements Runnable {
        private static final String TAG = "SendNotificationTask";

        @Override
        public void run() {
            CloudAccount account = new CloudAccount(getApplicationContext().getString(R.string.AccessKey), getApplicationContext().getString(R.string.AccessKeySecret), getApplicationContext().getString(R.string.Endpoint));
            MNSClient client = account.getMNSClient();

            try {
                Log.d(TAG, "doInBackground: inside try");
                CloudQueue queue = client.getQueueRef(getApplicationContext().getString(R.string.QueueName_2));// replace with your queue name
                Log.d(TAG, "doInBackground: inside for loop :: ");
                Message message = new Message();
                message.setMessageBody(ntfcnTxt); // use your own message body here
                Message putMsg = queue.putMessage(message);
                Log.d(TAG, "Send message id is: " + putMsg.getMessageId());

                handler.post(new Runnable() {
                    public void run() {
                        progressDialog.setMessage("Notification Sent");
                        opText.setText("Notification sent.");
                        progressDialog.dismiss();
                    }
                });
            } catch (ClientException ce) {
                Log.d(TAG, "sendButton: Something wrong with the network connection between client and MNS service.Please check your network and DNS availablity.");
                ce.printStackTrace();
            } catch (ServiceException se) {
                if (se.getErrorCode().equals("QueueNotExist")) {
                    Log.d(TAG, "sendButton: Queue is not exist.Please create before use");
                } else if (se.getErrorCode().equals("TimeExpired")) {
                    Log.d(TAG, "sendButton: The request is time expired. Please check your local machine timeclock");
                }
                se.printStackTrace();
            } catch (Exception e) {
                Log.d(TAG, "sendButton: Unknown exception happened!");
                e.printStackTrace();
            }


        }
    }


}

Then Create a class named "ReceiveService" and cope the below code.

package sample.alibabacloud.notificationdemo;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.MNSClient;

import java.util.concurrent.atomic.AtomicBoolean;

import sample.alibabacloud.notificationdemo.asynctasks.RcvNtfcnTask;

/**
 * Created by Sarath Chandra
 */

public class ReceiveService extends Service {

    private final static String TAG = "ReceiveService";
    private final IBinder myBinder = new LocalBinder();

    public ReceiveService(){

    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {

        Log.d(TAG, "onBind: IBinder onBind Method");
        return myBinder;
    }


    public class LocalBinder extends Binder {
        public ReceiveService getService() {
            Log.d(TAG, "getService:");
            return ReceiveService.this;
        }
    }


    public void stpMsgTask(){
        Log.d(TAG, "stpMsgTask: Stop message task is called");
        RcvNtfcnTask.setContinueLoop(new AtomicBoolean(false));
        Log.d(TAG, "stpMsgTask: set atomic booelan to false");
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate:");
        

    }

    public void isBoundable(){
        Toast.makeText(this,"Yes, I am Boundable", Toast.LENGTH_LONG).show();
    }


    @Override
    public int onStartCommand(Intent intent,int flags, int startId){
        super.onStartCommand(intent, flags, startId);
        Log.d(TAG, "onStartCommand: ");
        //  Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
        new Thread(new Runnable() {
            @Override
            public void run() {

                serviceMethod();

            }
        }).start();

        return Service.START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        Log.d(TAG, "onDestroy: ScreenOnReceiver is unregistered");

    }



    public void serviceMethod(){

        CloudAccount account = new CloudAccount(getString(R.string.AccessKey), getString(R.string.AccessKeySecret), getString(R.string.Endpoint));
        MNSClient client = account.getMNSClient();
        RcvNtfcnTask receiveNotification = new RcvNtfcnTask(this);
        receiveNotification.execute(client);

    }

    @Override
    public boolean stopService(Intent name) {
        return super.stopService(name);
    }


}

15.Then, create a class named MessageReceiverand copy the below code

package sample.alibabacloud.notificationdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

/**
 * Created by Sarath Chandra
 */

public class MessageReceiver extends BroadcastReceiver {

    private final static String TAG = "MessageReceiver";

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "onReceive: MessageReceiver");
        context.startService(new Intent(context,ReceiveService.class));
    }



}

16.Create a package asynctasks package, and under that create a class called RcvNtfcnTask and copy this code.

package sample.alibabacloud.notificationdemo.asynctasks;

import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.os.AsyncTask;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.aliyun.mns.client.CloudQueue;
import com.aliyun.mns.client.MNSClient;
import com.aliyun.mns.common.ClientException;
import com.aliyun.mns.common.ServiceException;
import com.aliyun.mns.model.Message;

import java.util.concurrent.atomic.AtomicBoolean;

import sample.alibabacloud.notificationdemo.R;

/**
 * Created by Sarath Chandra
 */

public class RcvNtfcnTask extends AsyncTask<MNSClient, Integer, Void> {

    private final static String TAG = "ReceiveNotificationTask";
    private static AtomicBoolean continueLoop = new AtomicBoolean(true);

    private static AtomicBoolean getContinueLoop() {
        return continueLoop;
    }

    public static void setContinueLoop(AtomicBoolean continueLoop) {
        RcvNtfcnTask.continueLoop = continueLoop;
    }

    Context mContext;

    public RcvNtfcnTask(Context mContext) {
        this.mContext = mContext;
    }


    @Override
    protected Void doInBackground(MNSClient... mnsClients) {


        MNSClient client = mnsClients[0];

        int i = 101;
        while (getContinueLoop().get()) {


            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {

                CloudQueue queue = null;
                Message popMsg = null;

                try {
                    queue = client.getQueueRef(mContext.getString(R.string.QueueName_2));// replace with your queue name
                    popMsg = queue.popMessage();
                } catch (NoClassDefFoundError t) {
                    Log.d(TAG, "doInBackground: Throwable : " + t.getMessage());
                }

                if (popMsg != null) {
                    i++;
                    Log.d(TAG, "doInBackground: message handle: " + popMsg.getReceiptHandle());
                    Log.d(TAG, "doInBackground: message body: " + popMsg.getMessageBodyAsString());
                    Log.d(TAG, "doInBackground: message id: " + popMsg.getMessageId());
                    Log.d(TAG, "doInBackground: message dequeue count:" + popMsg.getDequeueCount());

                    Log.d(TAG, "doInBackground: msg Received" + popMsg.getMessageBodyAsString());
                    //remember to  delete message when consume message successfully.

                    NotificationCompat.Builder mBuilder =
                            new NotificationCompat.Builder(mContext)
                                    .setSmallIcon(R.mipmap.ic_launcher_round)
                                    .setContentTitle("Notification Demo")
                                    .setDefaults(Notification.DEFAULT_ALL)
                                    .setContentText(popMsg.getMessageBodyAsString());

                    NotificationManager mNotificationManager =
                            (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);

                    mNotificationManager.notify(i, mBuilder.build());
                    queue.deleteMessage(popMsg.getReceiptHandle());

                    Log.d(TAG, "doInBackground: delete message successfully");
                } else {
                    i = 101;
                    Log.d(TAG, "doInBackground: No message");
                }


            } catch (NoClassDefFoundError e) {
                Log.d(TAG, "doInBackground: No Class Def Dound Error");
                e.printStackTrace();
            } catch (ClientException ce) {
                Log.d(TAG, "doInBackground: Thre is a problem with network and client connection");
                ce.printStackTrace();
            } catch (ServiceException se) {
                if (se.getErrorCode().equals("QueueNotExist")) {
                    Log.d(TAG, "doInBackground: Queue is not exist.Please create queue before use");
                } else if (se.getErrorCode().equals("TimeExpired")) {
                    Log.d(TAG, "doInBackground: The request is time expired. Please check your local machine timeclock");
                }

            } catch (Exception e) {
                Log.d(TAG, "doInBackground: Unknown exception happened!");
                e.printStackTrace();
            }
        }
        return null;
    }


}

17.Then, create one more XML named inputdialog under res > layout, and copy the below code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_root"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="10dp" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Type Your Message : "
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editTextDialogUserInput"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <requestFocus />

    </EditText>

</LinearLayout>

18.That's it! If everything is done correctly, all your compilation issues will go away and the application starts installing by clicking the small play (run) button in the status bar of Android Studio.

07

Please take a look at my GitHub page for the final code repo and let me know if you face any issues, or raise any pull requests for improvements!

1 0 0
Share on

Alibaba Clouder

2,605 posts | 747 followers

You may also like

Comments

5079033106944676 August 5, 2018 at 3:33 pm

I have a quick question... can I use Alibaba Cloud Message Services or REST Services from a Xamarin Application.

Alibaba Clouder

2,605 posts | 747 followers

Related Products