android安卓开发问题集 XMPP篇
1、消息推送查了下资料,后面还是使用了androidpn
(1)java.security.KeyStoreException: KeyStore jks implementation not found
解决方法, 在创建ConnectionConfiguration 时指定证书位置及类型:
connConfig.setTruststorePath("/system/etc/security/cacerts.bks");
connConfig.setTruststoreType("bks");
(2) 客户端一些说明
asmack的代码以及jar可以从 http://code.google.com/p/asmack/downloads/list 下载.
在android中创建一个service用来管理连接以及处理报文.
创建连接代码如下 ,其中server_ip是jabber服务器的ip, 可以是域名.
Log.i(TAG, "ConnectManager in...");
ConnectionConfiguration connConfig = new ConnectionConfiguration(server_ip);
// connConfig.setSecurityMode(SecurityMode.disabled);
connConfig.setSecurityMode(SecurityMode.required);
connConfig.setSASLAuthenticationEnabled(false);
connConfig.setCompressionEnabled(false);
mConnection = new XMPPConnection(connConfig);
连接到服务器代码:
if (!isConnect()) {
Log.i(TAG, "Connect to server now...");
try {
// Connect to the server
mConnection.connect();
Log.i(TAG, "connect success!!!");
} catch (XMPPException e) {
Log.e(TAG, "connect failed!", e);
}
}
判断是否连接上:
mConnection.isConnected();
登录到服务器代码, 需要用户名和密码:
if (!isLogin()) {
Log.i(TAG, "Login to server now...");
try {
mConnection.login(username, passwd);
Log.i(TAG, "login success!!!");
} catch (XMPPException e) {
Log.e(TAG, "login failed!", e);
}
}
判断是否登录上:
mConnection.isAuthenticated();
添加连接监听代码:
mConnection.addConnectionListener(new ConnectionListener() {
public void connectionClosed() {
// TODO
}
public void connectionClosedOnError(Exception e) {
// TODO
}
public void reconnectingIn(int seconds) {
// Ignore
}
public void reconnectionFailed(Exception e) {
// Ignore
}
public void reconnectionSuccessful() {
// Ignore
}
});
添加包监听代码, 以名单列表为例:
PacketFilter rosterFilter = new PacketTypeFilter(RosterPacket.class);
mConnection.addPacketListener(new RosterPacketListener(), rosterFilter);
其中 RosterPacket类是继承Packet类的, 除此之外还有 IQ, Message, Presence, AuthMechanism, Response五种类型的包.
可以使用OrFilter来同时处理多种类型的包. 以下代码用来接收所有的包:
PacketFilter rosterPF = new PacketTypeFilter(RosterPacket.class);
PacketFilter IQPF = new PacketTypeFilter(IQ.class);
PacketFilter MSGPF = new PacketTypeFilter(Message.class);
PacketFilter PresencePF = new PacketTypeFilter(Presence.class);
PacketFilter AMPF = new PacketTypeFilter(AuthMechanism.class);
PacketFilter REPF = new PacketTypeFilter(Response.class);
OrFilter allPF = new OrFilter(rosterPF, IQPF);
allPF.addFilter(MSGPF);
allPF.addFilter(PresencePF);
allPF.addFilter(AMPF);
allPF.addFilter(REPF);
PacketListener myListener = new PacketListener() {
public void processPacket(Packet pk) {
Log.i(TAG, "receive message : " + pk.toString());
}
};
mConnection.addPacketListener(myListener, allPF);