0

I was trying to make a Service class which send Beacon ID to server and receiving response from server via MQTT too when the phone is nearby the beacon, and after that trigger the notification. But, I want every response topic, should be different to each user that send Beacon data to server via MQTT. The topic is the same topic to send request to server, but adding username at the back.

Example :
request topic = send_beacon
response topic = send_beacon/username

The result I want to be, the response message from server should trigger notificaton to come out. But somehow, the notification itself doesn't come out because method messageArrived() not receiving any message.

Here's my code

public class BackgroundService extends Service implements IMqttActionListener, MqttCallback, MqttTraceHandler {

    private void sleep(int ms) {
        try {
            Thread.sleep(ms);
        } catch (Exception ignored) {

        }
    }

    public void initMqttClient() {
        try {
            MqttConnectOptions conOpt = new MqttConnectOptions();
            MqttSettings.getInstance(getApplicationContext()).setConnectedEnabled(true);
            if(!getString(R.string.mqtt_user_id).isEmpty())
                conOpt.setUserName(getString(R.string.mqtt_user_id));
            if(!getString(R.string.mqtt_password).isEmpty())
                conOpt.setPassword(getString(R.string.mqtt_password).toCharArray());
            conOpt.setCleanSession(true);
            conOpt.setConnectionTimeout(MqttConnectOptions.CONNECTION_TIMEOUT_DEFAULT);
            conOpt.setKeepAliveInterval(MqttConnectOptions.KEEP_ALIVE_INTERVAL_DEFAULT);

            mqttClient = new MqttAndroidClient(getApplicationContext(),
                    "tcp://"+getString(R.string.mqtt_server_uri)+":"+getString(R.string.mqtt_server_port),
                    "beacon_"+ UUID.randomUUID().toString());
            mqttClient.registerResources(getApplicationContext());
            mqttClient.setCallback(this);
            mqttClient.setTraceCallback(this);
            mqttClient.connect(conOpt, null, this);

        } catch (MqttException e) {
            Log.e("MQTTERROR", e.getMessage());
            e.printStackTrace();
        }
    }

    private void showCustomerPromoNotification(int promo_id, String name) {
        Intent notificationIntent = new Intent(getApplicationContext(), PromotionActivity.class);
        notificationIntent.putExtra(PromotionActivity.PROMOTION_ID_EXTRA, promo_id);

        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent intent = PendingIntent.getActivity(getApplicationContext(), 0,
                notificationIntent, 0);

        Notification notification = new Notification.Builder(getApplicationContext())
                .setContentTitle("CAUTION !!!")
                .setContentText(name)
                .setSmallIcon(R.drawable.ic_logo)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_logo_big))
                .setContentIntent(intent)
                .build();

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(promo_id, notification);
    }

    private PowerManager.WakeLock wakeLock;

    private SharedPreferences sharedpreferences;

    private Beacon beacon;
    private List<Beacon> beacons;
    private MqttAndroidClient mqttClient;

    private String broadcast_data = "";

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

        PowerManager pm = (PowerManager) getSystemService(this.POWER_SERVICE);

        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNotSleep");

        sharedpreferences = getSharedPreferences(getString(R.string.preference_name), Context.MODE_PRIVATE);

        initMqttClient(); // Start MQTT Client (connecting & set subscribe)
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mqttClient != null) {
            try {
                Log.d("STOP", "Mqtt: disconnect");
                mqttClient.disconnect();
                mqttClient = null;
            } catch (MqttException e) {
                Log.e("STOP", "Mqtt:x disconnection error: ", e);
            }
        }

        beacon.disconnect(this);
    }

    public void onBeaconReagion(List<Beacon> list, BRegion bRegion) {
        this.beacons = list;

        String broadcast_msg;

        for (Beacon beacon : beacons) {
            int major = beacon.getMajor();
            int minor = beacon.getMinor();

            if(Double.compare(beacon.getAccuracy(), 3.0) > 0) continue;

            broadcast_msg = String.format(Locale.US, "%d,%s,%d,%d",
                    sharedpreferences.getInt(getString(R.string.pref_user_id), 0),
                    sharedpreferences.getString(getString(R.string.pref_token), ""),
                    major,
                    minor);
            try {
                if(sharedpreferences.getInt(getString(R.string.pref_user_group_id), 0) == 4) {
                    mqttClient.publish(getString(R.string.mqtt_publish_topic_customer), broadcast_msg.getBytes(), 1, false);
                }
                else {
                    mqttClient.publish(getString(R.string.mqtt_publish_topic_employee), broadcast_msg.getBytes(), 1, false);
                }
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
        sleep(1 * 30 * 1000); // Hold every 30 seconds
    }

    @Override
    public void connectionLost(Throwable cause) {

    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        Log.d("MQTTMSG", new String(mqttMessage.getPayload()));
        String[] message = new String(mqttMessage.getPayload()).split(",");
        int user_group_id = sharedpreferences.getInt(getString(R.string.pref_user_group_id), 0);
        try {
            Date last_notification_time = new Date(sharedpreferences.getLong(getString(R.string.pref_last_notification_time), 0));
            if (user_group_id == 4) { //TODO compare hours by 3 hours
                showCustomerPromoNotification(Integer.parseInt(message[0]), message[1]);
                Date date = new Date();
                sharedpreferences.edit().putLong(getString(R.string.pref_last_notification_time), date.getTime()).apply();
                mqttMessage.clearPayload();
            }
        }
        catch (NumberFormatException nfe) {
            nfe.printStackTrace();
        }
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {

    }

    @Override
    public void traceDebug(String tag, String message) {

    }

    @Override
    public void traceError(String tag, String message) {

    }

    @Override
    public void traceException(String tag, String message, Exception e) {

    }

    @Override
    public void onSuccess(IMqttToken asyncActionToken) {
        int user_group_id = sharedpreferences.getInt(getString(R.string.pref_user_group_id), 0);
        if(user_group_id == 4)
            try {
                mqttClient.subscribe(getString(R.string.mqtt_publish_topic_customer)+"/"+getString(R.string.pref_user_name), 1);
                Log.d("MQTTSUBS", "Subscribe to = "+getString(R.string.mqtt_publish_topic_customer)+"/"+sharedpreferences.getString(getString(R.string.pref_user_name), ""));
            } catch (MqttException e) {
                e.printStackTrace();
            }
    }

    @Override
    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {

    }

}

Thank you for your help

poring91
  • 393
  • 7
  • 22

0 Answers0