Reliable and Fast Messaging and Notification Services Using Alibaba Cloud Message Service for Android

简介: This is a sample project created to demonstrate the usage of Alibaba Cloud Message Service on Android.

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. You can find more information about this step on the documentation center.
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!

相关实践学习
RocketMQ一站式入门使用
从源码编译、部署broker、部署namesrv,使用java客户端首发消息等一站式入门RocketMQ。
消息队列 MNS 入门课程
1、消息队列MNS简介 本节课介绍消息队列的MNS的基础概念 2、消息队列MNS特性 本节课介绍消息队列的MNS的主要特性 3、MNS的最佳实践及场景应用 本节课介绍消息队列的MNS的最佳实践及场景应用案例 4、手把手系列:消息队列MNS实操讲 本节课介绍消息队列的MNS的实际操作演示 5、动手实验:基于MNS,0基础轻松构建 Web Client 本节课带您一起基于MNS,0基础轻松构建 Web Client
目录
相关文章
|
存储 缓存 JSON
Code For Better 谷歌开发者之声——Android 中的 Volley 库
Volley是一个HTTP 库,它使 Android 应用程序的网络变得非常简单和快速。它由 Google 开发并在 2013 年 Google I/O 期间推出。它的开发是因为 Android SDK 中缺少能够在不影响用户体验的情况下工作的网络类。尽管 Volley 是 Android 开源项目 (AOSP) 的一部分,但 Google 在 2017 年 1 月宣布 Volley 将迁移到一个独立的库。它管理网络请求的处理和缓存,并节省开发人员一次又一次编写相同的网络调用/缓存代码的宝贵时间。Volley不适合大型下载或流式操作,因为 Volley 在解析期间将所有响应保存在内存中。
100 0
|
Java Linux Android开发
windows编译FFmpeg for Android 和AndroidStudio使用FFmpeg(二)
FFmpeg的编译是一个大坑,尤其是编译安卓平台的动态库和静态库,应用于APP中。在Linux平台编译是相对简单的,但是我经过尝试在Linux编译静态库没有成功,所以又在windows平台尝试编译了ffempg的动态库,应用成功了,这里分享一下。
301 0
windows编译FFmpeg for Android 和AndroidStudio使用FFmpeg(二)
|
Linux Shell C语言
windows编译FFmpeg for Android 和AndroidStudio使用FFmpeg(一)
FFmpeg的编译是一个大坑,尤其是编译安卓平台的动态库和静态库,应用于APP中。在Linux平台编译是相对简单的,但是我经过尝试在Linux编译静态库没有成功,所以又在windows平台尝试编译了ffempg的动态库,应用成功了,这里分享一下。
438 0
windows编译FFmpeg for Android 和AndroidStudio使用FFmpeg(一)
|
IDE 开发工具 Android开发
解决This Gradle plugin requires a newer IDE able to request IDE model level 3. For Android Studio
解决This Gradle plugin requires a newer IDE able to request IDE model level 3. For Android Studio
127 0
解决This Gradle plugin requires a newer IDE able to request IDE model level 3. For Android Studio
|
存储 人工智能 Java
TensorFlow Lite for Android 初探(附demo)
TensorFlow Lite for Android 初探(附demo)
436 0
TensorFlow Lite for Android 初探(附demo)
|
开发工具 Android开发
License for package Android SDK Build-Tools 28.0.3 not accepted.
License for package Android SDK Build-Tools 28.0.3 not accepted.
271 0
License for package Android SDK Build-Tools 28.0.3 not accepted.
|
开发工具
Could not get unknown property ‘versions‘ for object of type com.android.build.gradle.AppExtension
Could not get unknown property ‘versions‘ for object of type com.android.build.gradle.AppExtension
1521 0
Could not get unknown property ‘versions‘ for object of type com.android.build.gradle.AppExtension
|
开发工具 Android开发
解决Error:Could not determine the class-path for interface com.android.builder.model.AndroidProject.
解决Error:Could not determine the class-path for interface com.android.builder.model.AndroidProject.
164 0
解决Error:Could not determine the class-path for interface com.android.builder.model.AndroidProject.
|
Java 程序员 开发工具
SAP BTP SDK for Android 已经支持 Kotlin 了
SAP BTP SDK for Android 已经支持 Kotlin 了
SAP BTP SDK for Android 已经支持 Kotlin 了
|
消息中间件 网络协议 物联网
微服务消息队列(MQTT For IoT)Android Demo使用介绍
目前阿里云官方对于微消息队列 MQTT提供了很多语言的参考示例,但是在实际的使用中发现很多用户在使用Android Sample的时候总是会遇到问题,无法正常调试使用。本文主要介绍Android Sample的使用。
微服务消息队列(MQTT For IoT)Android Demo使用介绍