Paho MQTT Android在服务中没有收到任何消息

时间:2017-07-24 12:06:24

标签: android mqtt paho

我正在尝试创建一个Service类,它将Beacon ID发送到服务器,并在手机靠近信标时通过MQTT接收来自服务器的响应,然后触发通知。但是,我希望每个响应主题都应该与通过MQTT将Beacon数据发送到服务器的每个用户不同。该主题与向服务器发送请求相同,但在后面添加用户名。

示例:
请求主题= send_beacon
回复主题= send_beacon/username

我想要的结果是,来自服务器的响应消息应该触发通知出来。但不知何故,通知本身并未出现,因为方法messageArrived()没有收到任何消息。

这是我的代码

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) {

    }

}

感谢您的帮助

0 个答案:

没有答案