Android平台基于asmack实现XMPP协议中的PubSub机制
Android平臺(tái)基于asmack實(shí)現(xiàn)XMPP協(xié)議中的PubSub機(jī)制
本文主要介紹,在Android平臺(tái)上基于asmack包,實(shí)現(xiàn)的PubSub機(jī)制,在PubSub中最重要的概念是節(jié)點(diǎn)Node,幾乎所有的操作都要通過(guò)Node來(lái)實(shí)現(xiàn):
1、創(chuàng)建節(jié)點(diǎn)
?public void createnode(String NodeID)
?{
?ConfigureForm form = new ConfigureForm(FormType.submit);
? ? ? ? ? form.setNodeType(NodeType.leaf);
? ? ? ? ? form.setAccessModel(AccessModel.open);
? ? ? ? ? form.setPublishModel(PublishModel.open);
? ? ? ? ? form.setPersistentItems(true);
? ? ? ? ? form.setNotifyRetract(true) ; ??
? ? ? ? ? form.setMaxItems(65535);?
? ? ?try?
? ? ? {
LeafNode my_leaf_node = manager.createNode(NodeID);
my_leaf_node.sendConfigurationForm(form);?
Log.i("MyError","創(chuàng)建成功");
? }?
? ? ?catch (XMPPException e)?
? ? ?{
? ? ?Log.i("MyError","創(chuàng)建失敗");
e.printStackTrace();
?} ?
? ? ?
?}
?
2、訂閱節(jié)點(diǎn)
?public void subscribe(String NodeID,final Context context)
?{
?try?
?{
LeafNode my_leaf_node = (LeafNode)manager.getNode(NodeID);
my_leaf_node.addItemEventListener(new ItemEventListener()?
?{
public void handlePublishedItems(ItemPublishEvent items)?
{ ?
? PayloadItem temp = (PayloadItem)items.getItems().get(0);
? Log.i("MyError","接收消息");
? //Toast.makeText(PictureActivity.this, "連接成功"+pubSubAddress, Toast.LENGTH_SHORT).show(); ?
}});
SubscribeForm subscriptionForm = new SubscribeForm(FormType.submit);
? ? ? ? subscriptionForm.setDeliverOn(true);
? ? ? ? subscriptionForm.setDigestFrequency(5000);
? ? ? ? subscriptionForm.setDigestOn(true);
? ? ? ? subscriptionForm.setIncludeBody(true);
? ??
? ? ? ? List<Subscription> subscriptions = my_leaf_node.getSubscriptions();
? ? ? ? ? ?
? ? ? ? ? ?boolean flag = true;
? ? ? ? ? ?for (Subscription s : subscriptions)
? ? ? ? ? ?{
? ? ? ? ? ? ? ?if (s.getJid().equalsIgnoreCase(connection.getUser()))
? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ?flag=false;
? ? ? ? ? ? ? ? break;
? ? ? ? ? ? ? ?}
? ? ? ? ? ?}
? ? ? ? ? ?
? ? ? ? ? ?
? ? ? ? ? ? ?if(flag)
? ? ? ? ? ? ?{
? ? ? ? ? ? my_leaf_node.subscribe(connection.getUser(), subscriptionForm);
? ? ? ? ? ? ?}
? ? ? ? ? ? ?Log.i("MyError","訂閱成功");
?}
?catch (XMPPException e)?
?{
?Log.i("MyError","訂閱失敗");
?e.printStackTrace();
?}
?}
3、發(fā)布消息
?public void publish(String NodeId,String title,String content)
?{
??
SimplePayload payload = new SimplePayload("picture","pubsub:test:picture", "<picture xmlns='pubsub:test:picture'><title>"+title+"</title><content>"+content+"</content></picture>");
PayloadItem item=new PayloadItem("voice-guide"+System.currentTimeMillis(), payload);
try?
{
LeafNode node = (LeafNode) manager.getNode(NodeId);
System.out.println(item.toXML());
?
node.publish(item);
Log.i("MyError","發(fā)布成功");
}?
catch (XMPPException e)?
{
Log.i("MyError","發(fā)布失敗成功");
e.printStackTrace();
}
? ??
? ?
?}
4、設(shè)置權(quán)限,非常重要,很多開(kāi)發(fā)者會(huì)忽視
public void setAFF(String NodeId,String Jid)//必須是Owner
?{
ArrayList<MyAffiliation> list = new ArrayList<MyAffiliation>();
? MyAffiliation affiliation ?= new MyAffiliation(Jid,Affiliation.Type.owner);
? list.add(affiliation);
? try?
? { ?
? LeafNode my_leaf_node = (LeafNode)manager.getNode(NodeId);
?
? Packet reply = SyncPacketSend.getReply(connection,?
? ? ? ? createPubsubPacket(pubSubAddress,Jid,Type.SET,new MyAffiliationsExtension(list,NodeId),
? ? PubSubNamespace.valueOf("OWNER")));
? Log.i("MyError","設(shè)置成功");
? }?
? catch (XMPPException e)?
{ ??
? Log.i("MyError","設(shè)置失敗");
e.printStackTrace();
}?
?
?}
? ? 源碼:
package com.baidu.mapapi.demo.pubsub;import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import java.util.ListIterator;import org.jivesoftware.smack.AndroidConnectionConfiguration; import org.jivesoftware.smack.SmackAndroid; import org.jivesoftware.smack.XMPPConnection; import org.jivesoftware.smack.XMPPException; import org.jivesoftware.smack.packet.Packet; import org.jivesoftware.smack.packet.PacketExtension; import org.jivesoftware.smack.packet.IQ.Type; import org.jivesoftware.smackx.pubsub.AccessModel; import org.jivesoftware.smackx.pubsub.Affiliation; import org.jivesoftware.smackx.pubsub.ConfigureForm; import org.jivesoftware.smackx.pubsub.FormType; import org.jivesoftware.smackx.pubsub.Item; import org.jivesoftware.smackx.pubsub.ItemPublishEvent; import org.jivesoftware.smackx.pubsub.LeafNode; import org.jivesoftware.smackx.pubsub.NodeExtension; import org.jivesoftware.smackx.pubsub.NodeType; import org.jivesoftware.smackx.pubsub.PayloadItem; import org.jivesoftware.smackx.pubsub.PubSubElementType; import org.jivesoftware.smackx.pubsub.PubSubManager; import org.jivesoftware.smackx.pubsub.PublishModel; import org.jivesoftware.smackx.pubsub.SimplePayload; import org.jivesoftware.smackx.pubsub.SubscribeForm; import org.jivesoftware.smackx.pubsub.Subscription; import org.jivesoftware.smackx.pubsub.listener.ItemEventListener; import org.jivesoftware.smackx.pubsub.packet.PubSub; import org.jivesoftware.smackx.pubsub.packet.PubSubNamespace; import org.jivesoftware.smackx.pubsub.packet.SyncPacketSend;import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.Toast;public class PubSubService {public String pubSubAddress;public PubSubManager manager;public AndroidConnectionConfiguration connConfig ;public XMPPConnection connection = new XMPPConnection(connConfig);public List<org.jivesoftware.smackx.pubsub.Subscription> SubscriptionItem;public Button sub ;public List<? extends Item> NodeItems;public List<XMLInfo> sceneryinfo = new ArrayList<XMLInfo>();public String str;public void login(String Ip,String username,String passwaord){//SmackAndroid.init(this); try {connConfig = new AndroidConnectionConfiguration(Ip, 5222);connection = new XMPPConnection(connConfig);connection.connect(); connection.login(username, passwaord);pubSubAddress = "pubsub."+ connection.getServiceName();manager = new PubSubManager(connection,pubSubAddress);Log.i("MyError","連接成功"); }catch (XMPPException e) {Log.i("MyError","連接失敗"); e.printStackTrace();}}public void createnode(String NodeID){ConfigureForm form = new ConfigureForm(FormType.submit);form.setNodeType(NodeType.leaf);form.setAccessModel(AccessModel.open);form.setPublishModel(PublishModel.open);form.setPersistentItems(true);form.setNotifyRetract(true) ; form.setMaxItems(65535); try {LeafNode my_leaf_node = manager.createNode(NodeID);my_leaf_node.sendConfigurationForm(form); Log.i("MyError","創(chuàng)建成功"); } catch (XMPPException e) {Log.i("MyError","創(chuàng)建失敗"); e.printStackTrace();} }public void subscribe(String NodeID,final Context context){try {LeafNode my_leaf_node = (LeafNode)manager.getNode(NodeID);my_leaf_node.addItemEventListener(new ItemEventListener() {public void handlePublishedItems(ItemPublishEvent items) { PayloadItem temp = (PayloadItem)items.getItems().get(0);Log.i("MyError","接收消息");//Toast.makeText(PictureActivity.this, "連接成功"+pubSubAddress, Toast.LENGTH_SHORT).show(); }});SubscribeForm subscriptionForm = new SubscribeForm(FormType.submit);subscriptionForm.setDeliverOn(true);subscriptionForm.setDigestFrequency(5000);subscriptionForm.setDigestOn(true);subscriptionForm.setIncludeBody(true);List<Subscription> subscriptions = my_leaf_node.getSubscriptions();boolean flag = true;for (Subscription s : subscriptions){if (s.getJid().equalsIgnoreCase(connection.getUser())){ flag=false;break;}}if(flag){my_leaf_node.subscribe(connection.getUser(), subscriptionForm);}Log.i("MyError","訂閱成功"); }catch (XMPPException e) {Log.i("MyError","訂閱失敗"); e.printStackTrace();}}public void publish(String NodeId,String title,String content){SimplePayload payload = new SimplePayload("picture","pubsub:test:picture", "<picture xmlns='pubsub:test:picture'><title>"+title+"</title><content>"+content+"</content></picture>");PayloadItem item=new PayloadItem("voice-guide"+System.currentTimeMillis(), payload);try {LeafNode node = (LeafNode) manager.getNode(NodeId);System.out.println(item.toXML());node.publish(item);Log.i("MyError","發(fā)布成功"); } catch (XMPPException e) {Log.i("MyError","發(fā)布失敗成功"); e.printStackTrace();}}public boolean mGetItems(String nodeID){ try {LeafNode node = (LeafNode) manager.getNode(nodeID);// node.deleteAllItems();SubscriptionItem=node.getSubscriptions(); String subscriptionId=null;for(int i=0;i<SubscriptionItem.size();i++){if(SubscriptionItem.get(i).getJid().equalsIgnoreCase(connection.getUser())){subscriptionId=SubscriptionItem.get(i).getId(); break;}}System.out.println( subscriptionId);NodeItems = node.getItems(8,"eBB5GyMzzQPAIgkMwnn4N3YkD6FN944Cu6Qsmz4h");System.out.println(NodeItems.size());Log.i("MyError","獲取成功"); } catch (XMPPException e) {Log.i("MyError","獲取失敗"); e.printStackTrace();return false;}try { ListIterator lit = NodeItems.listIterator();while(lit.hasNext()){PayloadItem a = (PayloadItem) lit.next();System.out.println( a.toXML().length()+"gbwx");if(a.toXML().length()>10000){File file = new File("/mnt/sdcard/MyPubSubXMl/getxml.xml");FileOutputStream fis = new FileOutputStream(file);fis.write(a.toXML().getBytes());fis.close();File file1 = new File("/mnt/sdcard/MyPubSubXMl/getxml.xml");FileInputStream inStream;inStream = new FileInputStream(file1);XMLInfo temp = PullPersonService.readXml(inStream).get(0);inStream.close();sceneryinfo.add(temp);}lit.next();}System.out.println( sceneryinfo.size()+"drdrdr");//File file2 = new File("/mnt/sdcard/BitGuide/xinjiao.jpg");//FileOutputStream fis2 = new FileOutputStream(file2);//MyPubSubImg .generateImage(sceneryinfo.get(0).getcontent(), fis2); }catch (Exception e) {Log.e("MyError","異常");e.printStackTrace();}return true;}public void setAFF(String NodeId,String Jid)//必須是Owner{ArrayList<MyAffiliation> list = new ArrayList<MyAffiliation>();MyAffiliation affiliation = new MyAffiliation(Jid,Affiliation.Type.owner);list.add(affiliation);try { LeafNode my_leaf_node = (LeafNode)manager.getNode(NodeId); Packet reply = SyncPacketSend.getReply(connection, createPubsubPacket(pubSubAddress,Jid,Type.SET,new MyAffiliationsExtension(list,NodeId),PubSubNamespace.valueOf("OWNER")));Log.i("MyError","設(shè)置成功"); } catch (XMPPException e) { Log.i("MyError","設(shè)置失敗"); e.printStackTrace();} }static PubSub createPubsubPacket(String to, String from,Type type, PacketExtension ext, PubSubNamespace ns) { PubSub request = new PubSub(); request.setTo(to); request.setType(type); request.setFrom(from);if (ns != null) { request.setPubSubNamespace(ns); } request.addExtension(ext); return request; } }class MyAffiliation implements PacketExtension { protected String jid; protected Affiliation.Type affiliation;public MyAffiliation(String jid, Affiliation.Type affiliation) { this.jid=jid; this.affiliation = affiliation; } public String getElementName() { return "affiliation"; } public String getNamespace() { return null; } public String toXML() { StringBuilder builder = new StringBuilder("<"); builder.append(getElementName()); appendAttribute(builder, "jid", jid); appendAttribute(builder, "affiliation", affiliation.toString()); builder.append("/>"); return builder.toString(); } private void appendAttribute(StringBuilder builder, String att, String value) { builder.append(" "); builder.append(att); builder.append("='"); builder.append(value); builder.append("'"); } } class MyAffiliationsExtension extends NodeExtension {protected List<MyAffiliation> affiliations = null;protected String node;public MyAffiliationsExtension(){super(PubSubElementType.AFFILIATIONS);}public MyAffiliationsExtension(List<MyAffiliation> subList,String node0){super(PubSubElementType.AFFILIATIONS);affiliations = subList;node=node0;}@Overridepublic String toXML(){if ((affiliations == null) || (affiliations.size() == 0)){return super.toXML();}else{StringBuilder builder = new StringBuilder("<");builder.append(getElementName());builder.append(" "); builder.append("node"); builder.append("='"); builder.append(node); builder.append("'"); builder.append(">");for (MyAffiliation item : affiliations){builder.append(item.toXML());}builder.append("</");builder.append(getElementName());builder.append(">");return builder.toString();}} }
總結(jié)
以上是生活随笔為你收集整理的Android平台基于asmack实现XMPP协议中的PubSub机制的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 中国现代书画家——张士高、崔世年、姚子华
- 下一篇: RuntimeError: Python