XiMengJianYu/.svn/pristine/a9/a9c95402e787f727357b46af148f342772c1794c.svn-base

71 lines
2.6 KiB
Plaintext
Raw Permalink Normal View History

2023-04-17 17:58:44 +08:00
package de.eclipsemagazin.mqtt.push;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
public class PushCallback implements MqttCallback {
private ContextWrapper context;
public PushCallback(ContextWrapper context) {
this.context = context;
}
@Override
public void connectionLost(Throwable cause) {
//We should reconnect here
}
@SuppressWarnings("deprecation")
@Override
public void messageArrived(MqttTopic topic, MqttMessage message) throws Exception {
final NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
final Notification notification = new Notification(R.drawable.snow,
"Black Ice Warning!", System.currentTimeMillis());
// Hide the notification after its selected
notification.flags |= Notification.FLAG_AUTO_CANCEL;
final Intent intent = new Intent(context, BlackIceActivity.class);
final PendingIntent activity = PendingIntent.getActivity(context, 0, intent, 0);
notification.setLatestEventInfo(context, "消息", "收到消息: " +
new String(message.getPayload()), activity);
String tag = new String(message.getPayload());
Log.e("tag", "messageArrived: " + new String(message.getPayload(), "utf-8"));
MessageBean bean = parse(tag);
Log.e("tag",bean.toString());
notification.number += 1;
notificationManager.notify(0, notification);
}
private MessageBean parse(String tag) throws JSONException {
MessageBean bean = new MessageBean();
JSONObject obj = new JSONObject(tag);
bean.setContent(obj.getString("content"));
bean.setExtensionNumber(obj.getString("extensionNumber"));
bean.setMessageFlag(obj.getString("messageFlag"));
bean.setRemark(obj.getString("remark"));
bean.setTitle(obj.getString("title"));
bean.setSendTime(obj.getString("sendTime"));
bean.setSextensionState(obj.getString("sextensionState"));
return bean;
}
@Override
public void deliveryComplete(MqttDeliveryToken token) {
//We do not need this because we do not publish
}
}