安卓开发之mqtt协议实例代码
首先物联网协议mqtt协议是基于tcp/ip协议的,使用了官方的mqttclient框架
/*
*初始化mqttclient
*/
privatevoidinit(){
try{
//MQTT的连接设置
options=newMqttConnectOptions();
//host为主机名,test为clientid即连接MQTT的客户端ID,一般以客户端唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
client=newMqttClient(newIp().host,username,
newMemoryPersistence());
//设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
options.setCleanSession(false);
//options.setWill(myTopic,null,2,false);
//设置连接的用户名
options.setUserName(login_token);
//设置连接的密码
options.setPassword(passWord.toCharArray());
//设置超时时间单位为秒
options.setConnectionTimeout(10);
//设置会话心跳时间单位为秒服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
options.setKeepAliveInterval(60);
//设置回调
client.setCallback(newMqttCallback(){
@Override
publicvoidconnectionLost(Throwablecause){
//连接丢失后,一般在这里面进行重连
System.out.println("connectionLost----------");
}
@Override
publicvoiddeliveryComplete(IMqttDeliveryTokentoken){
//publish后会执行到这里
System.out.println("deliveryComplete---------"
+token.isComplete());
}
@Override
publicvoidmessageArrived(StringtopicName,MqttMessagemessage)
throwsException{
byte[]message1=message.getPayload();
//subscribe后得到的消息会执行到这里面
System.out.println("messageArrived----------"+message1[0]+Arrays.toString(message1));
System.out.println(message1[0]==5);
Stringid=newString(subBytes(message1,1,16),"UTF-8");
System.out.print("mqtt收到的id"+id);
DeviceListdevice=getBookById(id);
System.out.print("device"+device.getName());
Stringname=device.getName();
StringgName=device.getgName();
Stringtype=device.getType();
System.out.print("名字为"+name+gName);
/**
*使用handler发送matt接收的消息,格式为二进制数据
**/
Messagemsg=newMessage();
msg.what=1;
if(message1[0]==1){
//msg.obj=name+"设备心跳";
//handler.sendMessage(msg);
return;
}
if(message1[0]==2){
msg.obj=gName+""+name+"报警";
msg.arg1=Integer.parseInt(type);
handler.sendMessage(msg);
return;
}
if(message1[0]==3){
msg.obj=gName+""+name+"上线";
handler.sendMessage(msg);
return;
}
if(message1[0]==4){
msg.obj=gName+""+name+"离线";
handler.sendMessage(msg);
return;
}
if(message1[0]==5){
if(message1[17]==0){
msg.obj=gName+""+name+"关门";
}else{
msg.obj=gName+""+name+"开门";
}
handler.sendMessage(msg);
return;
}
if(message1[0]==20&&message1[17]>0&&message1[17]<20){
msg.obj=name+"电池电量:"+message1[17]+"%";
handler.sendMessage(msg);
System.out.println("电池:"+name+"电池电量:"+message1[17]+"%");
return;
}
if(message1[17]>0){
SharedPreferencessp=getActivity().getSharedPreferences(id,getActivity().MODE_PRIVATE);
//获得sp的编辑器
SharedPreferences.Editored=sp.edit();
//以键值对的显示将用户名和密码保存到sp中
ed.putString("battery",String.valueOf(message1[17]));
//提交用户名和密码
ed.commit();
}
}
});
}catch(Exceptione){
e.printStackTrace();
}
}
publicbyte[]subBytes(byte[]src,intbegin,intcount){
byte[]bs=newbyte[count];
System.arraycopy(src,begin,bs,0,count);
returnbs;
}
//根据id拿到属性为id的Book对象。
publicstaticDeviceListgetBookById(Stringid){
DeviceListbook=newDeviceList();
book.setId(id);//设置传入的id值
//books.indexOf()根据id比较对象是否相等
returndeviceList1.get(deviceList1.indexOf(book));
//返回关联id的Book对象。
}
privatevoidconnect(){
newThread(newRunnable(){
@Override
publicvoidrun(){
try{
client.connect(options);
Messagemsg=newMessage();
msg.what=2;
handler.sendMessage(msg);
}catch(Exceptione){
e.printStackTrace();
Messagemsg=newMessage();
msg.what=3;
handler.sendMessage(msg);
}
}
}).start();
}
protectedbooleanonKeyDown(intkeyCode,KeyEventevent){
if(client!=null&&keyCode==KeyEvent.KEYCODE_BACK){
try{
client.disconnect();
}catch(Exceptione){
e.printStackTrace();
}
}
returnsuper.getActivity().onKeyDown(keyCode,event);
}
@Override
publicvoidonDestroy(){
super.onDestroy();
try{
scheduler.shutdown();
client.disconnect();
}catch(MqttExceptione){
e.printStackTrace();
}
}
privatevoidstartReconnect(){
scheduler=Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate(newRunnable(){
@Override
publicvoidrun(){
if(!client.isConnected()){
connect();
}
}
},0*1000,10*1000,TimeUnit.MILLISECONDS);
}
其次使用handlermessage接收消息,并已notifacation的形式展示在通知栏页面
handler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
super.handleMessage(msg);
if(msg.what==1){
NotificationManagermanager=(NotificationManager)getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
NotificationmyNotify=newNotification();
myNotify.icon=R.drawable.logo;
myNotify.tickerText="新消息";
myNotify.when=System.currentTimeMillis();
//使用默认的声音
myNotify.defaults|=Notification.DEFAULT_SOUND;
//使用默认的震动
myNotify.defaults|=Notification.DEFAULT_VIBRATE;
//使用默认的声音、振动、闪光
myNotify.defaults=Notification.DEFAULT_ALL;
//myNotify.flags=Notification.FLAG_AUTO_CANCEL;
//myNotify.flags=Notification.FLAG_NO_CLEAR;//不能够自动清除
RemoteViewsrv=newRemoteViews(getActivity().getPackageName(),
R.layout.activity_notification1);
rv.setTextViewText(R.id.tv_desc,(String)msg.obj);
myNotify.contentView=rv;
Intentintent=newIntent(getActivity(),MainActivity.class);
//intent.addCategory(Intent.CATEGORY_LAUNCHER);
//intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
android.app.PendingIntentcontentIntent=android.app.PendingIntent.getActivity(getActivity(),0,
intent,0);
myNotify.contentIntent=contentIntent;
manager.notify(i1++,myNotify);
PowerManagerpm=(PowerManager)getActivity().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLockwakeLock=pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP|
PowerManager.SCREEN_DIM_WAKE_LOCK,"target");
booleanscreen=pm.isScreenOn();
if(!screen){//如果灭屏
wakeLock.acquire();
wakeLock.release();
}
refresh();
}elseif(msg.what==2){
System.out.println("连接成功");
System.out.print("连接成功大小"+listDatas2.size());
try{
client.subscribe(myTopic,1);
client.subscribe(myTopic1,1);
}catch(MqttExceptione){
e.printStackTrace();
}
}elseif(msg.what==3){
//Toast.makeText(MainActivity.this,"连接失败,系统正在重连",Toast.LENGTH_SHORT).show();
System.out.println("连接失败,系统正在重连");
}
}
};
以上这篇安卓开发之mqtt协议实例代码就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。