如何实现Xmpp chat android

时间:2017-10-26 07:51:16

标签: android xmpp

我想在我的应用程序中想象xmpp连接我在google中引用了很多教程,但我没有明确的想法。       请一些人帮我解决这个问题,给出建议如何实现xmpp连接。

谢谢。

3 个答案:

答案 0 :(得分:6)

首先你必须添加build.gradle

compile "org.igniterealtime.smack:smack-android:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-tcp:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-im:4.1.0-rc1"
compile "org.igniterealtime.smack:smack-extensions:4.1.0-rc1"

然后创建LocalBinder类

public class LocalBinder<S>  extends Binder {
    private final WeakReference<S> mService;

    public LocalBinder(final S service) {
        mService = new WeakReference<S>(service);
    }

    public S getService() {
        return mService.get();
    }
}

然后创建服务类

    public class XmppService extends Service {

    public static MyXMPP xmpp;
    private String ServiceName = "", HostAddress = "";
    private String USERNAME = "";
    private String PASSWORD = "";
    private SessionManager sessionManager;

    @Override
    public IBinder onBind(final Intent intent) {
        return new LocalBinder<XmppService>(this);
    }

    @Override
    public boolean onUnbind(final Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate() {
        sessionManager = new SessionManager(XmppService.this);

        ServiceName = Your Service Name ;
        HostAddress = Your Host Address;

        USERNAME = your xmpp server user name;
        PASSWORD = Your xmpp server pwd;


        xmpp = MyXMPP.getInstance(XmppService.this, ServiceName, HostAddress, USERNAME, PASSWORD);
        xmpp.connect("onCreate");

    }

    @Override
    public int onStartCommand(final Intent intent, final int flags,
                              final int startId) {

        return Service.START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        MyXMPP.instance=null;
        MyXMPP.instanceCreated=false;

        xmpp.connection.disconnect();

        System.out.println("--------------Xmpp Service Stopped-----------");
    }

   }

创建xmpp类

    public class MyXMPP {

    public static boolean connected = false;
    public boolean loggedin = false;
    public static boolean isconnecting = false;
    public static boolean isToasted = true;
    private boolean chat_created = false;
    private boolean server_chat_created = false;
    private String serviceName = "", hostAddress = "";
    public static XMPPTCPConnection connection;
    public static String loginUser;
    public static String passwordUser;
    XmppService context;
    public static MyXMPP instance = null;
    public static boolean instanceCreated = false;
    private static ChatHandler chatHandler;

    public MyXMPP(XmppService context, String mServiceName, String mHostAddress, String loginUser, String passwordUser) {
        this.serviceName = mServiceName;
        this.hostAddress = mHostAddress;
        this.loginUser = loginUser;
        this.passwordUser = passwordUser;
        this.context = context;
        init();
    }

    public static  MyXMPP getInstance(XmppService context, String mServiceName, String mHostAddress, String user, String pass) {

        if (instance == null) {
            instance = new MyXMPP(context, mServiceName, mHostAddress, user, pass);
            instanceCreated = true;
        }
        return instance;

    }

    public org.jivesoftware.smack.chat.Chat Mychat ,MyServerchat;

    ChatManagerListenerImpl mChatManagerListener;
    MMessageListener mMessageListener;

    String text = "";
    String mMessage = "", mReceiver = "";

    static {
        try {
            Class.forName("org.jivesoftware.smack.ReconnectionManager");
        } catch (ClassNotFoundException ex) {
            // problem loading reconnection manager
        }
     }

     public void init() {
        mMessageListener = new MMessageListener(context);
        mChatManagerListener = new ChatManagerListenerImpl();
        initialiseConnection();
    }

    private void initialiseConnection() {

        XMPPTCPConnectionConfiguration.Builder config = XMPPTCPConnectionConfiguration.builder();
        config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
        config.setServiceName(serviceName);
        config.setHost(hostAddress);
        config.setDebuggerEnabled(true);
        config.setConnectTimeout(50000);

        XMPPTCPConnection.setUseStreamManagementResumptiodDefault(true);
        XMPPTCPConnection.setUseStreamManagementDefault(true);
        connection = new XMPPTCPConnection(config.build());
        XMPPConnectionListener connectionListener = new XMPPConnectionListener();
        connection.addConnectionListener(connectionListener);
    }

    public void disconnect() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                connection.disconnect();
            }
        }).start();
    }

     public void connect(final String caller) {

        AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() {
            @Override
            protected synchronized Boolean doInBackground(Void... arg0) {
                if (connection.isConnected())
                    return false;
                isconnecting = true;
                if (isToasted)
                    new Handler(Looper.getMainLooper()).post(new Runnable() {

                        @Override
                        public void run() {

                            /*Toast.makeText(context,
                                    caller + "=>connecting....",
                                    Toast.LENGTH_LONG).show();*/
                        }
                    });
                Log.d("Connect() Function", caller + "=>connecting....");

                 try {
                    connection.connect();

                     ReconnectionManager reconnectionManager = 
       ReconnectionManager.getInstanceFor(connection);
                    reconnectionManager.setEnabledPerDefault(false);
                    reconnectionManager.enableAutomaticReconnection();

                    /*PingManager pingManager = 
      PingManager.getInstanceFor(connection);
                    pingManager.setPingInterval(300);*/

                    DeliveryReceiptManager dm = DeliveryReceiptManager
                            .getInstanceFor(connection);
                    dm.setAutoReceiptMode(AutoReceiptMode.always);
                    dm.addReceiptReceivedListener(new ReceiptReceivedListener() 
      {

                        @Override
                        public void onReceiptReceived(final String fromid, final String toid, final String msgid,final Stanza packet) {

                        }
                    });
                    connected = true;

                } catch (IOException e) {
                    if (isToasted)
                        new Handler(Looper.getMainLooper())
                                .post(new Runnable() {

                                    @Override
                                    public void run() {

                                        /*Toast.makeText(context,"(" + caller + ")"+ "IOException: ", Toast.LENGTH_SHORT).show();*/
                                    }
                                });

                    Log.e("(" + caller + ")", "IOException: " + e.getMessage());
                } catch (SmackException e) {
                    new Handler(Looper.getMainLooper()).post(new Runnable() {

                        @Override
                        public void run() {
                            /*Toast.makeText(context, "(" + caller + ")" + "SMACKException: ", Toast.LENGTH_SHORT).show();*/
                        }
                    });
                    Log.e("(" + caller + ")",
                            "SMACKException: " + e.getMessage());
                } catch (XMPPException e) {
                    if (isToasted)

                        new Handler(Looper.getMainLooper())
                                .post(new Runnable() {
                                    @Override
                                    public void run() {
                                        /*Toast.makeText(context,"(" + caller + ")"+ "XMPPException: ",Toast.LENGTH_SHORT).show();*/
                                    }
                                });
                    Log.e("connect(" + caller + ")","XMPPException: " + e.getMessage());
                }
                return isconnecting = false;
            }
        };
        connectionThread.execute();
     }

    public void login() {

        try {
            System.out.println("----login------USERNAME------------" + loginUser);
            System.out.println("----login------PASSWORD------------" + passwordUser);

             connection.login(loginUser, passwordUser);
            Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");

        } catch (XMPPException | SmackException | IOException e) {
            e.printStackTrace();
      //      connect("");
        } catch (Exception e) {
        }
    }

     private class ChatManagerListenerImpl implements ChatManagerListener {
        @Override
        public void chatCreated(final org.jivesoftware.smack.chat.Chat chat,final boolean createdLocally) {
            if (!createdLocally)
                chat.addMessageListener(mMessageListener);
        }
    }

    public int sendMessage(String senderID, String mMessage) {

        if (!chat_created) {
            Mychat = ChatManager.getInstanceFor(connection).createChat(senderID, mMessageListener);
            chat_created = true;
        }
        final Message message = new Message();
        message.setBody(mMessage);
        message.setStanzaId(String.format("%02d", new Random().nextInt(1000)));
        message.setType(Message.Type.chat);

        try {
            if (connection.isAuthenticated()) {
                Mychat.sendMessage(message);
                return 1;
            } else {
                login();
                return 0;
            }
        } catch (SmackException.NotConnectedException e) {

            Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
            return 0;

        } catch (Exception e) {

            Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
            return 0;
        }

       /* try {
            if (connection.isAuthenticated()) {
                Mychat.sendMessage(message);
            } else {
                login();
            }
        } catch (NotConnectedException e) {
            Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");

        } catch (Exception e) {
            Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
        }*/
    }


    public int sendMessageServer(String senderID, String mMessage) {

        if (!server_chat_created) {
            MyServerchat = 
    ChatManager.getInstanceFor(connection).createChat(senderID, mMessageListener);
            server_chat_created = true;
        }


        final Message message = new Message();
        message.setBody(mMessage);
        message.setStanzaId(String.format("%02d", new Random().nextInt(1000)));
        message.setType(Message.Type.chat);
        try {
            if (connection.isAuthenticated()) {

                MyServerchat.sendMessage(message);
                return 1;
            } else {
                login();
                return 0;
            }
        } catch (SmackException.NotConnectedException e) {

            Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");
            return 0;

        } catch (Exception e) {

            Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
            return 0;
        }

       /* try {
            if (connection.isAuthenticated()) {
                Mychat.sendMessage(message);
            } else {
                login();
            }
        } catch (NotConnectedException e) {
            Log.e("xmpp.SendMessage()", "msg Not sent!-Not Connected!");

        } catch (Exception e) {
            Log.e("xmpp Message Exception", "msg Not sent!" + e.getMessage());
        }*/
    }

        public class XMPPConnectionListener implements ConnectionListener {
        @Override
        public void connected(final XMPPConnection connection) {

            Log.d("xmpp", "Connected!");
            connected = true;
            if (!connection.isAuthenticated()) {
                login();
            }
        }

        @Override
        public void connectionClosed() {
            if (isToasted)

                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub

                        /*Toast.makeText(context, "ConnectionCLosed!",
                                Toast.LENGTH_SHORT).show();*/

                    }
                });
            Log.d("xmpp", "ConnectionCLosed!");

            System.out.println("-------------ConnectionCLosed!----------------");
            instance = null;
            connected = false;
            chat_created = false;
            server_chat_created = false;
            loggedin = false;
        }

        @Override
        public void connectionClosedOnError(Exception arg0) {
            if (isToasted)

                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        /*Toast.makeText(context, "ConnectionClosedOn Error!!",
                                Toast.LENGTH_SHORT).show();*/

                    }
                });
            Log.d("xmpp", "ConnectionClosedOn Error!");
            connected = false;
            instance = null;
            chat_created = false;
            server_chat_created = false;
            loggedin = false;
        }

          @Override
         public void reconnectingIn(int arg0) {

            Log.d("xmpp", "Reconnectingin " + arg0);

            System.out.println("----------prem Reconnectingin----------------" + arg0);

            loggedin = false;
        }

        @Override
        public void reconnectionFailed(Exception arg0) {
            if (isToasted)

                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        /*Toast.makeText(context, "ReconnectionFailed!",Toast.LENGTH_SHORT).show();*/
                    }
                });
            Log.d("xmpp", "ReconnectionFailed!");
            connected = false;
            instance = null;
            chat_created = false;
            server_chat_created = false;
            loggedin = false;
        }

        @Override
        public void reconnectionSuccessful() {
            if (isToasted)

                new Handler(Looper.getMainLooper()).post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        /*Toast.makeText(context, "REConnected!",Toast.LENGTH_SHORT).show();*/
                    }
                });
            Log.d("xmpp", "ReconnectionSuccessful");
            connected = true;

            chat_created = false;
            server_chat_created = false;
            loggedin = false;
        }

        @Override
        public void authenticated(XMPPConnection arg0, boolean arg1) {
            Log.d("xmpp", "Authenticated!");
            loggedin = true;

            ChatManager.getInstanceFor(connection).addChatListener(mChatManagerListener);

            chat_created = false;
            server_chat_created = false;
            new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            }).start();
            if (isToasted)
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        /*Toast.makeText(context, "Connected!",Toast.LENGTH_SHORT).show();*/
                    }
                });
        }
    }

    private class MMessageListener implements ChatMessageListener {

        public MMessageListener(Context contxt) {
        }

        @Override
        public void processMessage(final org.jivesoftware.smack.chat.Chat chat,final Message message) 
        {
            Log.i("MyXMPP_MESSAGE_LISTENER", "Xmpp message received: '"+ message);

            if (message.getType() == Message.Type.chat && message.getBody() != null) 
            {
                System.out.println("-----------xmpp message-------------" + message.getBody());
                try 
                {
                    if (chatHandler == null) {
                        chatHandler = new ChatHandler(context);
                    }
                    chatHandler.onHandleChatMessage(message);
                } 
                catch (Exception e) {
                }
            }
        }
    }
}

下一步处理来自xmpp类的接收数据

public class ChatHandler {

private Context context;
private IntentService service;
private GEODBHelper myDBHelper;
private SessionManager session;
public ChatHandler(Context context, IntentService service) {
    this.context = context;
    this.service = service;
    session = new SessionManager(context);
    myDBHelper = new GEODBHelper(context);
}
public ChatHandler(Context context) {
    this.context = context;
    session = new SessionManager(context);
    myDBHelper = new GEODBHelper(context);

}
public void onHandleChatMessage(Message message) {
    try {
        String data = URLDecoder.decode(message.getBody(), "UTF-8");
        JSONObject messageObject = new JSONObject(data);
    } 
    catch (Exception e) {
    }
}

添加到清单

<service
    android:name="com.app.xmpp.XmppService"
    android:enabled="true" />

启动xmpp服务

startService(new Intent(myclass.this, XmppService.class));

停止xmpp服务

stopService(new Intent(getApplicationContext(), XmppService.class));

答案 1 :(得分:2)

您可以集成Quickblox API,它具有多种功能,例如用户管理聊天群聊视频&amp;音频呼叫

Quickblox

答案 2 :(得分:1)

试试这个例子https://github.com/blikoon/Rooster 它对我有用。我使用这个来源做了我自己的使者 Goog运气