安卓使用mqtt

引入mqtt-client-0.4.1.jar包,然后写一个class(里面为mqtt的主要代码),如:

package com.example.htalka.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttPersistenceException;
import org.eclipse.paho.client.mqttv3.MqttSecurityException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence;


import com.example.htalka.MainActivity;
import com.example.htalka.R;
import com.example.htalka.application.HTalkApplication;
import com.example.htalka.helper.Const;
import com.example.htalka.helper.PrefUtil;
import com.example.htalka.model.Chat;
import com.example.htalka.model.User;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;


public class MQTTService extends Service implements MqttCallback{

public static String MQTT_HOST = "192.168.13.118";
public static int MQTT_PORT = 1883;


private static final String TAG = "MQTTService";
private static MqttClient client = null;
private MqttConnectOptions options = null;



// MQTT Client 参数
private String host;
private int port;
private String username;
private String password;
private int keepAlive;
private Boolean cleanSession;
private String clientID;

public static String CLINET_ID = "client_id";
public static String USER_ID = "user_id";
public static String TO_USER_ID = "to_user_id";
public static String TO_USER_LIST = "to_user_list";

public MQTTClientCallback clientCallback;
private ArrayList to_user_list;

public static HTalkApplication app;

/**
* 获取整个application

* @return
*/
public HTalkApplication getStuffApplication() {
return (HTalkApplication) this.getApplicationContext();
}

/**
* 初始化application
*/
public void initStuffApplication() {
app = getStuffApplication();
}

public void setMQTTClientCallback(MQTTClientCallback l) {
clientCallback = l;
}

/**
* MQTTClient回调

* @author Thierry
*/
public interface MQTTClientCallback {

public void connectLostCallBack();

public void msgArrivedCallBack(String topic, String string);

public void deliveryCompleteCallBack(IMqttDeliveryToken token);

}


/**
* Class for clients to access. Because we know this service always runs in
* the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public MQTTService getService() {
return MQTTService.this;
}
}

private NotificationManager mNotificationManager;

@Override
public void onCreate() {
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}

/**
* 初始化
*/
public void init() {
Log.v("post", "init---mqtt---");
this.host = Const.MQTT_HOST;
this.port = Const.MQTT_PORT;
this.cleanSession = false;
this.keepAlive = 30;
try {
String serverURI = "tcp://" + this.host + ":" + this.port;
// host为主机名,clientId即连接MQTT的客户端ID,一般以客户端唯一标识符表示,MemoryPersistence设置clientId的保存形式,默认为以内存保存
client = new MqttClient(serverURI, this.clientID, new MemoryPersistence());
// MQTT的连接设置
options = new MqttConnectOptions();
// 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
options.setCleanSession(this.cleanSession);
// 设置连接的用户名
// if (this.username != "") {
// Log.d(MQTTPlugin.TAG, "this.username:" + this.username);
// options.setUserName(this.username);
// }
// // 设置连接的密码
// if (this.password != "")
// options.setPassword(this.password.toCharArray());
// 设置超时时间 单位为秒
options.setConnectionTimeout(10);
// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
options.setKeepAliveInterval(this.keepAlive);
// 设置回调
client.setCallback(this);

// client.connect(options);
startConnect();



} catch (Exception e) {
e.printStackTrace();
}
}

@Override  
    public void onStart(Intent intent, int startId) {  


}

/**
* 开始进行连接到MQTT Server

* @throws MqttException
* @throws MqttSecurityException
*/
public void startConnect() throws MqttSecurityException, MqttException {
Log.v(TAG, "Start connect----------");
client.connect(options);
}


/**
* 断开MQTT连接

* @throws MqttException
*/
public void disConnect() throws MqttException {
Log.v(TAG, "dis connect----------");
client.disconnect();
}

/***
* 订阅

* @param topic
* @param qos
* @throws MqttException
*/
public void subscribe(String topic, int qos) throws MqttException {
Log.d(TAG, "subscribe=>topic:" + topic + "qos:" + qos);
Log.d("post", "subscribe=>topic:" + topic + "qos:" + qos);
client.subscribe(topic, qos);
}


/**
* 取消订阅

* @param topic
* @throws MqttException
*/
public void unsubscribe(String topic) throws MqttException {
client.unsubscribe(topic);
}


/**
* 取消所有订阅

* @throws MqttException
*/
public void unsubscribeAllTopics() throws MqttException {
Log.d(TAG, "un subscribe All Topics");
client.disconnect();
options.setCleanSession(true);
client.connect(options);
client.disconnect();
options.setCleanSession(this.cleanSession);

}

/**
* 发布消息

* @param topic
* @param payload
* @param qos
* @throws MqttException
* @throws MqttPersistenceException
*/
public static void publish(String to_user_id, String topic, String payload, int qos) throws MqttPersistenceException, MqttException {
MqttMessage msg = new MqttMessage();
msg.setPayload(payload.getBytes());
msg.setQos(qos);
client.publish(topic, msg);

}

// This is the object that receives interactions from clients. See
// RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.v(TAG, "on Bind start ");
if (intent != null) {
initStuffApplication();
this.clientID = intent.getExtras().getString(CLINET_ID);
this.to_user_list = intent.getExtras().getStringArrayList(TO_USER_LIST);
init();
try {
subscribeAll(this.to_user_list);
} catch (MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// stopped, so return sticky.
return mBinder;
}

//   +1/2/# 别人的/自己的 String user_id, 
public void subscribeAll(ArrayList to_user_list) throws MqttException{

String topic = "";
for(int i = 0; i < to_user_list.size(); ++i){
topic ="+/" + to_user_list.get(i) + "/" + PrefUtil.getUserId(this) + "/#";
subscribe(topic, Const.MQTT_QOS);
}
}

// /1/2 自己的/别人的 String user_id, 
public void publishMsg(String to_user_id, String msg) throws MqttPersistenceException, MqttException{
String topic = "/" + PrefUtil.getUserId(this) + "/" + to_user_id;
publish(to_user_id, topic, msg, Const.MQTT_QOS);
}


@Override
public void connectionLost(Throwable arg0) {
// TODO Auto-generated method stub
Log.i(TAG, "Connection Lost----------");
Log.i("post", "Connection Lost----------" +arg0.getCause());
// clientCallback.connectLostCallBack();
}

@Override
public void deliveryComplete(IMqttDeliveryToken token) {
// TODO Auto-generated method stub
Log.i(TAG, "Delivery Complete----------" + token.isComplete());
// clientCallback.deliveryCompleteCallBack(token);
}

@Override
public void messageArrived(String topic, MqttMessage msg) throws Exception {
// TODO Auto-generated method stub
Log.i(TAG, "Message Arrived----------topic:" + topic + "=>msg:" + msg.toString());
Log.v("post", "Message Arrived----------topic:" + topic + "=>msg:" + msg.toString());

//   /1/2  别人的/自己的 String user_id, 
topic = topic.substring(1, topic.length());
int endIndex = topic.indexOf('/');
String to_user_id = topic.substring(0, endIndex);
Log.v("post", "Message Arrived----------to_user_id:" + to_user_id);
Chat chat = new Chat();
chat.setTalk_Content(msg.toString()); 
SimpleDateFormat  formatter =  new SimpleDateFormat("yyyy年MM月dd日   HH:mm:ss");     
Date curDate = new Date(System.currentTimeMillis());//获取当前时间       
chat.setTalkTime(formatter.format(curDate));
User user = app.getUser(Long.valueOf(to_user_id));
Log.v("post", "Message Arrived----------to_user_id:" + user.getUserName());
chat.setTalker_Icon(user.getPhotoPath());
chat.setTalkerName(user.getUserName());
chat.setUserId(Long.valueOf(to_user_id));
chat.setType(Const.CHAT_TYPE_OTHERS);
app.addChat(chat);
showNotification(user.getUserName(), formatter.format(curDate), msg.toString());
// clientCallback.msgArrivedCallBack(topic, msg.toString());
// if (EWChat.isShowNoti && topic.startsWith("chat")) {
// //仅当处于后台且是会话消息时才有notification
// showNotification();
// }
}

@Override
public boolean onUnbind(Intent intent) {
Log.v(TAG, "MQTT service on Unbind");
try {
disConnect();
} catch (MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cancelNotification();
return super.onUnbind(intent);
}


@Override
public void onDestroy() {
// Cancel the persistent notification.
Log.v(TAG, "MQTT service on Destroy");
cancelNotification();
super.onDestroy();
// Tell the user we stopped.
}

/**
* Show a notification while this service is running.消息到达的时候给用户提醒
*/
@SuppressWarnings("deprecation")
public void showNotification(String user_name, String time, String msg) {
Log.i("post", "show Notification...");
// int iconId = getResources().getIdentifier("icon", "drawable", getPackageName());
//  
int iconId = R.drawable.chats;
CharSequence tickerText = time + "来自 "+ user_name;
CharSequence contentTitle = "HTalkA";
CharSequence contentText = msg;
 
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Notification notification = new Notification();
notification.when = System.currentTimeMillis();
notification.flags = Notification.FLAG_NO_CLEAR;//FLAG_AUTO_CANCEL;
        // 这个标识将通知放入通知的正在运行栏目 
        notification.flags |= Notification.FLAG_ONGOING_EVENT; 
        notification.flags |= Notification.FLAG_SHOW_LIGHTS; 
        notification.defaults = Notification.DEFAULT_LIGHTS; 
notification.defaults |= Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;
notification.icon = iconId;
notification.tickerText = tickerText;
// notification.contentView = new RemoteViews(this.getPackageName(), R.layout.custom_notifition); 
// notification.contentView.setTextViewText(R.id.notifition_content, "消息到啦"); 
// notification.contentView.setTextViewText(R.id.notifition_time, "2014-03-02 19:03:33"); 
 
notification.setLatestEventInfo(this, contentTitle, contentText, contentIntent);
// notification的id使用发送者的id
mNotificationManager.notify(1, notification);
}

/**
* cancel notification
*/
public void cancelNotification() {
mNotificationManager.cancelAll();
}
}


在一个activity中,通过bindservice的方式start mqtt的service。

如:

public static MQTTService service = null;

public static ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName arg0, IBinder binder) {
// TODO Auto-generated method stub
service = ((LocalBinder) binder).getService();
Log.v("post", "mqtt service--");
}

@Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
try {
service.disConnect();
} catch (MqttException e) {
e.printStackTrace();
}
service = null;
}
};


调用的时候:

Intent serviceIntent = new Intent(MainActivity.this, MQTTService.class);
Log.v("post", "user_client_" + PrefUtil.getUserId(this));
serviceIntent.putExtra(MQTTService.CLINET_ID,
"talka_user_client_" + PrefUtil.getUserId(this));

serviceIntent.putExtra(MQTTService.TO_USER_LIST, to_user_list);

this.bindService(serviceIntent, serviceConnection,
Context.BIND_AUTO_CREATE);

停止mqtt service

try {
service.unsubscribeAllTopics();
stopService(new Intent(LogoutActivity.this, MQTTService.class));
} catch (MqttException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

你可能感兴趣的:(安卓开发)