【发布时间】:2015-07-27 16:06:55
【问题描述】:
我想开发一个即时通讯应用程序。 GCM,用于推送数据是一种流行(且有效)的方式,如果你在 android 上,但由于以下原因我没有使用它:
- 它会删除 100 多条未送达的消息。
- 它不适用于没有谷歌应用的设备。
相反,我决定设置一个传统的 XMPP 服务器 (openFire),并使用 Smack api(TCP 连接)进行连接。到目前为止,一切进展顺利,但我有一些担忧。
这是我写的一个小测试代码(它在服务中运行):
Log.d("TAG","service has started");
SmackConfiguration.setDefaultPacketReplyTimeout(10000);
XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
.setUsernameAndPassword("admin", "football100")
.setServiceName("harsh-pc")
.setHost("192.168.0.200")
.setPort(5222).setSecurityMode(ConnectionConfiguration.SecurityMode.disabled)
.build();
final AbstractXMPPConnection conn2 = new XMPPTCPConnection(config);
try {
conn2.connect();
conn2.login();
Presence presence = new Presence(Presence.Type.available);
presence.setStatus("online");
// Send the packet (assume we have an XMPPConnection instance called "con").
conn2.sendStanza(presence);
} catch (SmackException | IOException | XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("TAG", e.toString());
}
StanzaFilter filter=new StanzaFilter() {
@Override
public boolean accept(Stanza stanza) {
return true;
}
};
StanzaListener listener= new StanzaListener() {
@Override
public void processPacket(Stanza packet) throws SmackException.NotConnectedException {
Log.d("TAG","recevied stuff");
ChatManager chatmanager = ChatManager.getInstanceFor(conn2);
Chat newChat = chatmanager.createChat("harsh@harsh-pc");
newChat.sendMessage("Reply :) ");
}
};
conn2.addAsyncStanzaListener(listener,filter);
ChatManager chatmanager = ChatManager.getInstanceFor(conn2);
Chat newChat = chatmanager.createChat("harsh@harsh-pc");
try {
Random r=new Random();
// newChat.sendMessage(Integer.toString(r.nextInt()));
Thread.sleep(1500);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("TAG",e.toString());
}
}
}).start();
final Thread sleeper=new Thread(new Runnable() {
@Override
public void run() {
for(;;){
try {
Thread.sleep(100000);
Log.d("TAG","SLEEPI");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});sleeper.start();
注意这个 sn-p 的最后一部分。 我必须运行一个无限循环,以便我可以继续侦听传入的数据包(如果我不包含此代码,我将无法拦截任何传入的数据包)。
我的问题是:
- 这种方法会消耗大量电池吗?
- 此方法会阻止设备休眠吗?
- 有没有更好的方法来完成任务(不使用 GCM)?
- 有没有办法将 GCM 与 OPENFIRE 集成?
【问题讨论】:
标签: java android push-notification xmpp