1. Are you ready for the Galaxy S20? Here is everything we know so far!

Run AWSiotMqtt subscription in android service

Discussion in 'Android Lounge' started by amar94, Sep 21, 2019.

  1. amar94

    amar94 Lurker
    Thread Starter

    Hi all,
    I want run aws iot mqtt subscription in android service. When i was run the application in device,app didn't get message which is sent from client.
    My service file:

    public class NotificationService extends Service {

    private AWSIotMqttManager mqttManager;
    Context context;
    SharedPreferences sharedPreferences;
    String clientId;
    public NotificationService(){

    }

    @override
    public void onCreate() {
    super.onCreate();
    sharedPreferences = getSharedPreferences("ClientId",Context.MODE_PRIVATE);
    clientId = sharedPreferences.getString("id","");
    Log.d(LOG_TAG,"ClientId =="+clientId);
    }

    @nullable
    @override
    public IBinder onBind(Intent intent) {
    return null;
    }

    @override
    public int onStartCommand(Intent intent, int flags, int startId) {
    startMqttSubscription();
    return START_STICKY;
    }

    private void startMqttSubscription() {
    mqttManager = new AWSIotMqttManager(clientId,"end-point");
    Log.d(LOG_TAG,"**message service is created**");
    try {
    mqttManager.subscribeToTopic("home/frontdoor/lock", AWSIotMqttQos.QOS0, new AWSIotMqttNewMessageCallback() {
    @override
    public void onMessageArrived(String topic, byte[] data) {
    try {
    String msg = new String(data,"UTF-8");
    Log.d(LOG_TAG,"message"+msg);
    Log.d(LOG_TAG,"topic"+topic);
    Toast.makeText(getApplicationContext(),"messages arrived="+msg,Toast.LENGTH_SHORT).show();
    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    }
    }
    });
    } catch (Exception e) {
    Log.e(LOG_TAG, "Subscription error.", e);
    }

    }

    @override
    public void onDestroy() {
    super.onDestroy();
    }
    }
    Please can anybody help me.
     


Loading...

Share This Page

Loading...