Androidpn裡的Xmpp的理解(訊息推送)
阿新 • • 發佈:2019-01-23
XMPP(可擴充套件通訊和表示協議)是基於可擴充套件標記語言(XML)的協議,它用於即時訊息(IM)以及線上探測。這個協議可能最終允許因特網使用者向因特網上的其他任何人傳送即時訊息。用xmpp來實現android的push功能,感覺有點大材小用了,xmpp本身是一種即時通訊協議。
xmpp是一種用於即時通訊的協議,使用過程有點類似於我們使用QQ的過程,其使用過程分為三步:
1. 連線伺服器,就好像開啟QQ軟體,看程式碼:
- if(!mXmppManager.isConnected()) {
-
ConnectionConfiguration config = new ConnectionConfiguration(mHost, mPort);
- config.setSecurityMode(SecurityMode.required);
- config.setSASLAuthenticationEnabled(false);
- config.setCompressionEnabled(false);
- XMPPConnection connection = new XMPPConnection(config);
- mXmppManager.setConnection(connection);
- try {
- connection.connect();
-
Log.i(LOGTAG, "XMPP connected successfully"
- /**
- * 這個就是對於通訊的xml文字進行解析的解析器,再把資訊轉換成IQ,這個相當於QQ的聊天資訊
- * 如果要用這個協議,其IQ的子類和IQProvider要進行重寫
- */
- ProviderManager.getInstance().addIQProvider("notification",
- "androidpn:iq:notification",
- new NotificationIQProvider());
-
} catch
- Log.d(LOGTAG, "the connection is error ... ");
- }
- mXmppManager.runTask();
- } else {
- Log.i(LOGTAG, "XMPP connected already");
- mXmppManager.runTask();
- }
這一步主要是連線伺服器,還有設定一些連線的引數,還有設定連線的解析器。
2. 如果沒有使用者,註冊新的帳號和密碼
- if(!mXmppManager.isRegistered()){
- final String newUsername = newRandomUUID();
- final String newPassword = newRandomUUID();
- Registration registration = new Registration();
- PacketFilter packetFilter = new AndFilter(new PacketIDFilter(
- registration.getPacketID()), new PacketTypeFilter(
- IQ.class));
- PacketListener packetListener = new PacketListener() {
- @Override
- publicvoid processPacket(Packet packet) {
- // 伺服器回覆客戶端
- if(packet instanceof IQ) {
- IQ response = (IQ) packet;
- if(response.getType() == IQ.Type.ERROR) { // 註冊失敗
- if (!response.getError().toString().contains(
- "409")) {
- Log.e(LOGTAG,"Unknown error while registering XMPP account! " + response.getError().getCondition());
- }
- } elseif(response.getType() == IQ.Type.RESULT) { // 註冊成功
- mXmppManager.setUsername(newUsername);
- mXmppManager.setPassword(newPassword);
- // 把使用者名稱和密碼都儲存到磁碟
- Editor editor = mSharedPrefs.edit();
- editor.putString(Contants.XMPP_USERNAME, newUsername);
- editor.putString(Contants.XMPP_PASSWORD, newPassword);
- editor.commit();
- mXmppManager.runTask();
- }
- }
- }
- };
- // 給註冊的Packet設定Listener,因為只有等到正真註冊成功後,我們才可以交流
- mConnection.addPacketListener(packetListener, packetFilter);
- registration.setType(IQ.Type.SET);
- registration.addAttribute("username", newUsername);
- registration.addAttribute("password", newPassword);
- // 向伺服器端,傳送註冊Packet包,注意其中Registration是Packet的子類
- mConnection.sendPacket(registration);
- } else { // 已經註冊過了
- mXmppManager.runTask();
- }
只要連線了伺服器了,客戶端就可以向伺服器端傳送訊息,傳送是以Packet(資料包)來進行傳送的,這個類有很多的子類,註冊的子類為Registration。
還有要注意的是,上面的addPacketListener方法不是給所有傳送的資料包設定listener,而只是針對這次的註冊Packet。
3. 用註冊的帳號和密碼進行登陸(像用QQ號帳進行登陸一樣)
- // 判斷是否已經登陸過了,是否是在登陸狀態
- if(!mXmppManager.isAuthenticated()) {
- try {
- mConnection.login(mUsername, mPassword, "AndroidpnClient");
- // 設定XmppConnection的監聽器
- if(mXmppManager.getConnectionListener() != null) {
- mConnection.addConnectionListener(mXmppManager.getConnectionListener());
- }
- // 設定伺服器端推送的監聽器
- PacketFilter packetFilter = new PacketTypeFilter(NotificationIQ.class);
- PacketListener packetListener = mXmppManager.getNotificationPacketListener();
- mConnection.addPacketListener(packetListener, packetFilter);
- mXmppManager.runTask();
- } catch (XMPPException e) {
- // 登陸失敗,應該重試
- String INVALID_CREDENTIALS_ERROR_CODE = "401";
- String errorMessage = e.getMessage();
- // 如果只是因為沒有註冊,則進行重新註冊
- if (errorMessage != null && errorMessage.contains(INVALID_CREDENTIALS_ERROR_CODE)) {
- mXmppManager.reregisterAccount();
- return;
- }
- mXmppManager.startReconnectionThread();
- } catch (Exception e) { // 有可能mConnection都為空
- Log.e(LOGTAG, "LoginTask.run()... other error");
- Log.e(LOGTAG, "Failed to login to xmpp server. Caused by: " + e.getMessage());
- mXmppManager.startReconnectionThread(); // 啟動重連執行緒
- }
- } else {
- mXmppManager.runTask();
- }
這裡設定了連線的監聽器mConnection.addConnectionListener(),連線過程中有可以連線突然中斷,連接出錯等等問題,要進行監聽。
設定伺服器推送資訊的Listener,接收到資訊後,顯示給使用者。
如果出錯的原因是401(無效的使用者名稱和密碼,則應該進行重新註冊,再連線)
對於伺服器push過來的資訊進行處理,是在PacketListener類裡面,這個接口裡,只要實現一個方法processPacket(Packet packet),從傳過來的Packet(資料包)裡獲取自己需要的資料:
- publicvoid processPacket(Packet packet) {
- if(packet instanceof NotificationIQ) {
- NotificationIQ notification = (NotificationIQ) packet;
- if(notification.getChildElementXML().contains("androidpn:iq:notification")) {
- String notificationId = notification.getId();
- String notificationApiKey = notification.getApiKey();
- String notificationTitle = notification.getTitle();
- String notificationMessage = notification.getMessage();
- String notificationUri = notification.getUri();
- Intent intent = new Intent(Contants.ACTION_SHOW_NOTIFICATION);
- intent.putExtra(Contants.NOTIFICATION_ID, notificationId);
- intent.putExtra(Contants.NOTIFICATION_API_KEY,notificationApiKey);
- intent.putExtra(Contants.NOTIFICATION_TITLE,notificationTitle);
- intent.putExtra(Contants.NOTIFICATION_MESSAGE, notificationMessage);
- intent.putExtra(Contants.NOTIFICATION_URI, notificationUri);
- mXmppManager.getContext().sendBroadcast(intent);
- }
- }
- }