在 MainActivity android 中使用 smack API 与服务器连接

Posted

技术标签:

【中文标题】在 MainActivity android 中使用 smack API 与服务器连接【英文标题】:Connecting with server using smack API in MainActivity android 【发布时间】:2016-08-18 07:32:58 【问题描述】:

我正在尝试使用 Smack API 接收和发送消息,但由于某些线程问题可能无法在单独的类中完成。但是当我现在移植 MainActivity 中的所有代码时,我将无法与服务器建立连接。下面是我的 MainActivity.class。

public class chatActivity extends AppCompatActivity 
    private static final String DOMAIN = "192.168.0.109";
    private static final String HOST = "192.168.0.109";
    private static final int PORT = 5222;
    private String userName ="";
    private String passWord = "";
    AbstractXMPPConnection connection ;
    ChatManager chatmanager ;
    Chat newChat;
    ChatManager chatManager;
    XMPPConnectionListener connectionListener = new XMPPConnectionListener();
    private boolean connected;
    private boolean isToasted;
    private boolean chat_created;
    private boolean loggedin;
    Context context;
    private MultiUserChat multiUserChat;
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        Thread t = new Thread(new Runnable() 
            @Override
            public void run() 
                init("user123","user123");
            
        );
t.start();

    

    public void init(String userId,String pwd ) 
        Log.i("XMPP", "Initializing!");
        this.userName = userId;
        this.passWord = pwd;
        this.context = context;
        XMPPTCPConnectionConfiguration.Builder configBuilder = XMPPTCPConnectionConfiguration.builder();
        configBuilder.setUsernameAndPassword(userName, passWord);
        configBuilder.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
        configBuilder.setResource("android");
        configBuilder.setServiceName(DOMAIN);
        configBuilder.setHost(HOST);
        configBuilder.setPort(PORT);
        //configBuilder.setDebuggerEnabled(true);
        connection = new XMPPTCPConnection(configBuilder.build());
        connection.addConnectionListener(connectionListener);

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

            Log.d("xmpp", "Connected!");
            connected = true;


            if (!connection.isAuthenticated()) 
                System.out.println("Hellooooooooo11111");
                login();

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

                    @Override
                    public void run() 
//                        // TODO Auto-generated method stub
//new MainActivity().updateText(context);

                    
                );

            
        

        @Override
        public void connectionClosed() 
            if (isToasted)

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

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


                    
                );
            Log.d("xmpp", "ConnectionCLosed!");
            connected = false;
            chat_created = false;
            loggedin = false;
        

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

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

                    @Override
                    public void run() 

                    
                );
            Log.d("xmpp", "ConnectionClosedOn Error!");
            connected = false;

            chat_created = false;
            loggedin = false;
        

        @Override
        public void reconnectingIn(int arg0) 

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

            loggedin = false;
        

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

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

                    @Override
                    public void run() 



                    
                );
            Log.d("xmpp", "ReconnectionFailed!");
            connected = false;

            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



                    
                );
            Log.d("xmpp", "ReconnectionSuccessful");
            connected = true;

            chat_created = false;
            loggedin = false;
        

        @Override
        public void authenticated(XMPPConnection arg0, boolean arg1) 
            Log.d("xmpp", "Authenticated!");
            loggedin = true;
            //  joinChatRoom();
            //  sendMsg();
            chat_created = false;
            //sendMessage("body","jid");
            //sendMsg();
            new Thread(new Runnable() 

                @Override
                public void run() 
                    try 
                        Thread.sleep(500);
                        //   sendMsg();
                     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



                    
                );
        
    
    public void login() 

        try 
            connection.login(userName, passWord);
            //  sendMsg();
            //Log.i("LOGIN", "Yey! We're connected to the Xmpp server!");

         catch (XMPPException | SmackException | IOException e) 
            e.printStackTrace();
         catch (Exception e) 
        

    

我的问题是如何使用 smack API,我完全不知道如何在主类中处理此网络操作。 我也尝试过在异步中运行它。

【问题讨论】:

【参考方案1】:

好的,我找到了我忘记在我的主类中添加以下方法的解决方案。

public void connectConnection()
    
        AsyncTask<Void, Void, Boolean> connectionThread = new AsyncTask<Void, Void, Boolean>() 

            @Override
            protected Boolean doInBackground(Void... arg0) 

                // Create a connection
                try 
                    connection.connect();
                    login();
                    connected = true;

                 catch (IOException e) 
                 catch (SmackException e) 

                 catch (XMPPException e) 
                

                return null;
            
        ;
        connectionThread.execute();
    

【讨论】:

以上是关于在 MainActivity android 中使用 smack API 与服务器连接的主要内容,如果未能解决你的问题,请参考以下文章

setAdapter() 在 android studio 中使 android 应用程序崩溃

如何在 Flutter 中使 StatusBar 对 Android 透明

Android如何在ListView中使EditText可编辑

如何在listview android中使文本颜色透明?

如何在android中使位图不可见? [关闭]

在android中使按钮半透明[重复]