1.broadcast
1.broadcast定义
Broadcast Receiver 为Android系统的四大组件之一。由广播发送者和广播接收者两部分组成。作用如下:
1.在同一应用之内或者不同应用之间的不同组件之间进行通信。
2.当有电话呼入时,或者当数据网络可用的时候,App可以收到此广播并且进行响应。
3.broadcast广播可以在于Service和Activity中使用。
1.1 broadcast发送者
- broadcast发送工具类
package mqtt;
import android.util.Log;
import android.content.Context;
import android.content.Intent;
/**
* Created by Max on 2018/11/22.
*/
public class BroadCastUtils {
public static void sendMqttSendBroadCast(Context ctx,String tts){
if(tts==null)return;
//Constant.Intent.Action_mqtt_send为String字符串常量
Intent intent = new Intent(Constant.Intent.Action_mqtt_send);
//Intent.putExtra (String name, String value/object value)
intent.putExtra("tts",tts);
ctx.sendBroadcast(intent);
}
}
Intent
- 一种消息传播机制,Intent可以在进程间发送结构化的消息。因此,可以通过实现Broadcast Receiver来监听和响应应用程序内的这些Broadcast Intent。
- Broadcast Intent用于向监听器通知系统的应用程序或应用程序事件,从而可以扩展应用程序间的事件驱动的编程模型。
- Broadcast Intent可以使应用程序更加开放;通过使用Intent来广播一个事件,可以在不用修改原始应用程序的情况下,让你和第三方开发人员对事件做出反应。在应用程序中,可以通过监听Broadcast Intent来对设备状态变化和第三方应用程序事件做出反应。
- 调用工具类
/**
Base64.encodeToString(keyValue, Base64.DEFAULT) 为android.util包中,将byte[]以Base64编码并返回String
**/
BroadCastUtils.sendMqttSendBroadCast(getActivity().getApplicationContext(), Base64.encodeToString(keyValue, Base64.DEFAULT));
1.2 broadcast接收者
register()和unRegister()需要在 onCreate()和onDestroy()内注册
@Override
public void onCreate() {
super.onCreate();
start();
register();
}
@Override
public void onDestroy() {
super.onDestroy();
unRegister();
}
private void register() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Constant.Intent.Action_mqtt_send);
registerReceiver(mReceiver,intentFilter);
}
private void unRegister(){
unregisterReceiver(mReceiver);
}
mReceiver接收
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG,"收到Mqtt消息");
String action = intent.getAction();
//匹配intent
if(Constant.Intent.Action_mqtt_send.equals(action)) {
//获取intent内的消息
String sendMsg = intent.getStringExtra("mqtt_send");
Log.d("mReceiver", "sendMsg "+sendMsg);
//对消息封装成json类型
String sendJson = getJson(sendMsg);
Log.i("mReceiver", sendJson);
//publishMessage(sendMsg);
if(sendMsg==null||sendMsg.isEmpty())return;
else {
//异步任务将sendjson发送出去
DelMqttRecvAsyTask task = new DelMqttRecvAsyTask(sendJson);
task.execute((Void) null);
}
}
}
};
由于发送数据是一个耗时操作,所以需要异步任务来完成。
public class DelMqttRecvAsyTask extends AsyncTask<Void, Void, Boolean> {
private final String data;
DelMqttRecvAsyTask(String data) {
this.data = data;
}
@Override
protected Boolean doInBackground(Void... params) {
//这里面写自己的任务,必须重写
publishMessage(this.data);
return true;
}
@Override
protected void onPostExecute(final Boolean success) {
if (success) {
} else {
}
}
@Override
protected void onCancelled() {
}
}
2. mqtt消息
简介:
MQTT协议(Message Queuing Telemetry Transport),翻译过来就是遥信消息队列传输,是IBM公司于1999年提出的,现在最新版本是3.1.1。MQTT是一个基于TCP的发布订阅协议,设计的初始目的是为了极有限的内存设备和网络带宽很低的网络不可靠的通信,非常适合物联网通信。
转自:https://baijiahao.baidu.com/s?id=1608411516249221334&wfr=spider&for=pc
package com.mqtt;
import org.eclipse.paho.client.mqttv3.DisconnectedBufferOptions;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
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.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
public class MyMqttServiceAndroid extends Service{
private static final String TAG = "SpeechnlgMqttService";
//自己的订阅主题
private static final String TOPIC_TO_QA = "";
//发布消息的主题
private static final String publishTopic = "";
//发送消息主题的网址
public static final String HOST = "";
//mqtt服务器所用的用户名和密码 可用Apache Apollo
private static final String username = "root";
private static final String password = "123456";
private static MqttClient client = null;
private MqttConnectOptions options;
private String clientId = "";
private MqttCallback cbk;
public MyMqttServiceAndroid() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
public void start() {
clientId = HSystemConfigInfo.getSerialId();
try {
// host为主机名,clientid即连接MQTT的客户端ID,一般以唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
client = new MqttClient(HOST, this.clientId, new MemoryPersistence());
// MQTT的连接设置
options = new MqttConnectOptions();
// 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
options.setCleanSession(true);
options.setAutomaticReconnect(true);
// 设置连接的用户名
options.setUserName(username);
// 设置连接的密码
options.setPassword(password.toCharArray());
// 设置超时时间 单位为秒
options.setConnectionTimeout(10);
// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
options.setKeepAliveInterval(20);
// 设置回调
if(this.cbk==null) {
client.setCallback(new MqttCallback() {
@Override
public void messageArrived(String topic, MqttMessage msg) throws Exception {
// TODO Auto-generated method stub
String payload = new String(msg.getPayload());
Log.i(TAG,topic+";"+payload);
sendRecvMsg(payload);//接受到的消息,发出去
}
@Override
public void deliveryComplete(IMqttDeliveryToken arg0) {
// TODO Auto-generated method stub
}
@Override
public void connectionLost(Throwable arg0) {
// TODO Auto-generated method stub
Log.i(TAG,"connection lost "+arg0.getMessage());
}
});
}
else
client.setCallback(this.cbk);
MqttTopic topic = client.getTopic(TOPIC_TO_QA);
//setWill方法,如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
options.setWill(topic, "close".getBytes(), 2, true);
client.connectWithResult(options).setActionCallback(new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken asyncActionToken) {
Log.i(TAG,"connect sucess!");
}
@Override
public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
Log.i(TAG,"connect failed!");
}
});
//订阅消息
int[] Qos = {2};
client.subscribe(TOPIC_TO_QA, Qos[0]);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 发布消息
*/
public void publishMessage(String msg) {
try {
MqttMessage message = new MqttMessage();
message.setPayload(msg.getBytes());
if(client!=null&&client.isConnected())
client.publish(publishTopic, message);
Log.d(TAG, "publishMessage: Message Published: " + msg);
} catch (MqttException e) {
Log.d(TAG, "publishMessage: Error Publishing: " + e.getMessage());
e.printStackTrace();
}
}
我是用的是Apache Apollo mqtt服务器。上面mqtt推送消息,接收消息可以用我上传的测试程序测试https://download.csdn.net/download/xyz86443/11002161 不知道怎么改c币,可以留言找我要