aws-amplify / aws-sdk-android

AWS SDK for Android. For more information, see our web site:
https://docs.amplify.aws
Other
1.03k stars 550 forks source link

Run mqtt subscription in android service #1209

Closed amarpulli1994 closed 5 years ago

amarpulli1994 commented 5 years ago

I m going to run mqtt subscription in android service. When i was run the application, getting null object refernce. My service file:

public class NotificationService extends Service {

    private AWSIotMqttManager mqttManager;
    Context context;
    public NotificationService(){

    }

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

    }

    private void showMessage(String topic, String msg) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setContentTitle(topic)
                .setContentText(msg);
        Intent intent = new Intent(this,MainActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(MainActivity.class);
        stackBuilder.addNextIntent(intent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(resultPendingIntent);
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(100, builder.build());

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            mqttManager.subscribeToTopic("home/frontdoor/lock", AWSIotMqttQos.QOS0,
                    new AWSIotMqttNewMessageCallback() {
                        @Override
                        public void onMessageArrived(final String topic, final byte[] data) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        String message = new String(data, "UTF-8");
                                        Log.d(LOG_TAG, "Message arrived:");
                                        Log.d(LOG_TAG, "Topic: " + topic);
                                        Log.d(LOG_TAG, " Message: " + message);

                                        Toast.makeText(context,"Arrived Messages are:"+message,Toast.LENGTH_SHORT).show();

                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(LOG_TAG, "Message encoding error.", e);
                                    }
                                }
                            });
                        }
                    });
        } catch (Exception e) {
            Log.e(LOG_TAG, "Subscription error.", e);
        }
        return START_STICKY;
    }

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

Log files:

2019-09-20 18:29:24.490 15522-15522/com.edgefinity.smartlock ```
E/com.edgefinity.smartlock.MainActivity: Subscription error.
    java.lang.NullPointerException: Attempt to invoke virtual method 'void com.amazonaws.mobileconnectors.iot.AWSIotMqttManager.subscribeToTopic(java.lang.String, com.amazonaws.mobileconnectors.iot.AWSIotMqttQos, com.amazonaws.mobileconnectors.iot.AWSIotMqttNewMessageCallback)' on a null object reference
        at com.edgefinity.smartlock.NotificationService.onStartCommand(NotificationService.java:64)
        at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:3539)
        at android.app.ActivityThread.-wrap20(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1744)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:6662)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
mutablealligator commented 5 years ago

@amarpulli1994 Thank you for reporting to us. You need to create the AWSIotMqttManager object before using it. See https://github.com/awslabs/aws-sdk-android-samples/blob/master/AndroidPubSub/src/com/amazonaws/demo/androidpubsub/PubSubActivity.java#L207 for further details.

AWSIotMqttManager mqttManager = new AWSIotMqttManager(clientId, endpoint);
amarpulli1994 commented 5 years ago

@kvasukib thnaks for response, I tried initialization AWSIotMqttmanager in android service like below way

String clientId = UUID.randomUUID().toString();
        Log.d(LOG_TAG,"ClientId =="+clientId);
        mqttManager = new AWSIotMqttManager(clientId,"end point");
        Log.d(LOG_TAG,"**message service is created**");
        try {
            Log.d(LOG_TAG,"**mqtt subscription created**");
            mqttManager.subscribeToTopic("home/frontdoor/lock", AWSIotMqttQos.QOS0,
                    new AWSIotMqttNewMessageCallback() {
                        @Override
                        public void onMessageArrived(final String topic, final byte[] data) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        String message = new String(data, "UTF-8");
                                        showMessage(topic,message);
                                        Log.d(LOG_TAG, "Message arrived:");
                                        Log.d(LOG_TAG, "Topic: " + topic);
                                        Log.d(LOG_TAG, "Message: " + message);
                                        Toast.makeText(context,"Arrived Messages are:"+message,Toast.LENGTH_SHORT).show();
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(LOG_TAG, "Message encoding error.", e);
                                    }
                                }
                            });
                        }
                    });
        } catch (Exception e) {
            Log.e(LOG_TAG, "Subscription error.", e);
        }

But when i was publish the message from one client, didn't get any message which is sent from client.

mutablealligator commented 5 years ago

@amarpulli1994 You need to establish a MQTT connection for publications and subscriptions to work. Please look at the docs for more information.

stale[bot] commented 5 years ago

This issue has been automatically closed because of inactivity. Please open a new issue if are still encountering problems.