MQTT的协议在Android的思实现
1、项目创建 2、在mainfests添加权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
3、在APP的级别下添加依赖包
implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.0'
implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
4、我这里使用的是服务状态下接收MQTT,然后创建MQTTService 继承Service并实现Service的实现类 4、实现MTQQ的方法,我这里都放到了一个service里(不想手敲就直接复制使用就得了)
public class MQTTService extends Service {
@SuppressLint("StaticFieldLeak")
public static MqttAndroidClient mqttAndroidClient;
public static MqttConnectOptions mMqttConnectOptions;
public static String HOST = "tcp://192.168.73.128:1883";
public static String USERNAME = "root";
public static String PASSWORD = "123123";
public static final String TAG = MQTTService.class.getSimpleName();
public static String PUBLISH_TOPIC = "/sys/Android/0001/thing/sservice/property/xifa";
public static String ONCLICK_PUBLISH_TOPIC = "/sys/a1l5AvjQHJc/0001/thing/event/property/post";
public static String RESPONSE_TOPIC = "message_arrived";
public String CLIENTID = "dasdad";
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
init_sensor();
return super.onStartCommand(intent, flags, startId);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
public static void startService(Context mContext) {
mContext.startService(new Intent(mContext, MQTTService.class));
}
public static void publish(String message) {
Integer qos = 2;
Boolean retained = false;
try {
mqttAndroidClient.publish(PUBLISH_TOPIC, message.getBytes(), qos.intValue(), retained.booleanValue());
} catch (MqttException e) {
e.printStackTrace();
}
}
@RequiresApi(api = Build.VERSION_CODES.O)
private void init_sensor() {
String serverURI = HOST;
mqttAndroidClient = new MqttAndroidClient(this, serverURI, CLIENTID);
mqttAndroidClient.setCallback(mqttCallback1);
mMqttConnectOptions = new MqttConnectOptions();
mMqttConnectOptions.setCleanSession(true);
mMqttConnectOptions.setConnectionTimeout(10);
mMqttConnectOptions.setKeepAliveInterval(20);
mMqttConnectOptions.setUserName(USERNAME);
mMqttConnectOptions.setPassword(PASSWORD.toCharArray());
boolean doConnect = true;
String message = "{\"terminal_uid\":\"" + CLIENTID + "\"}";
String topic = PUBLISH_TOPIC;
Integer qos = 2;
Boolean retained = false;
if ((!message.equals("")) || (!topic.equals(""))) {
try {
mMqttConnectOptions.setWill(topic, message.getBytes(), qos.intValue(), retained.booleanValue());
} catch (Exception e) {
Log.i(TAG, "Exception Occured", e);
doConnect = false;
iMqttActionListener.onFailure(null, e);
}
}
if (doConnect) {
doClientConnection();
}
}
private void doClientConnection() {
if (!mqttAndroidClient.isConnected() && isConnectIsNormal()) {
try {
mqttAndroidClient.connect(mMqttConnectOptions, null, iMqttActionListener);
} catch (MqttException e) {
e.printStackTrace();
}
}
}
private boolean isConnectIsNormal() {
ConnectivityManager connectivityManager = (ConnectivityManager) this.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
String name = info.getTypeName();
Log.e(TAG, "当前网络名称:" + name);
return true;
} else {
Log.i(TAG, "没有可用网络");
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doClientConnection();
}
}, 3000);
return false;
}
}
private IMqttActionListener iMqttActionListener = new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken arg0) {
Log.i(TAG, "连接成功 ");
try {
mqttAndroidClient.subscribe(ONCLICK_PUBLISH_TOPIC, 2);
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(IMqttToken arg0, Throwable arg1) {
arg1.printStackTrace();
Log.i(TAG, "连接失败 ");
doClientConnection();
}
};
private MqttCallback mqttCallback1 = new MqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage message) throws Exception {
String s = new String(message.getPayload());
Log.e("access",""+s);
}
@Override
public void deliveryComplete(IMqttDeliveryToken arg0) {}
@Override
public void connectionLost(Throwable arg0) {
Log.i(TAG, "连接断开 ");
doClientConnection();
}
};
public static void response(String message) {
String topic = RESPONSE_TOPIC;
Integer qos = 0;
Boolean retained = false;
try {
mqttAndroidClient.publish(topic, message.getBytes(), qos.intValue(), retained.booleanValue());
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void onDestroy() {
try {
mqttAndroidClient.disconnect();
} catch (MqttException e) {
e.printStackTrace();
}
super.onDestroy();
}
}
5、记得在mainfest里添加下面的服务,这包的MqttService,不是自己创建的,添加自己创建的MQTTServie服务
<service android:name=".MQTTService"/>
<service android:name="org.eclipse.paho.android.service.MqttService" />
|