有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Asmack Android与服务器Xmpp的连接中出现java错误

我无法连接到服务器我不知道为什么请帮助我。这是我的代码:

public class Sample extends Activity{

    /** Called when the activity is first created. */
    TextView tvHello;
    XMPPTCPConnection connection;
    ConnectionConfiguration config;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvHello = (TextView) findViewById(R.id.tvHello);
        Log.i("ohyeah", "I'm here");
        config = new ConnectionConfiguration("host", 5222, "servername");
        connection = new XMPPTCPConnection(config);
        try {

           connection.connect();
            // tvHello.setText("Connected to XMPP server");
            Log.i("ohyeah", "Successfully Connected");
        } catch (XMPPException e) {

            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.e("ohyeah", "Not Connected");
        } catch (SmackException e) {

            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.i("ohyeah", "Something Fishy");
        } catch (IOException e) {

            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.i("ohyeah", "yes");
        }
    }
}

这是我的错误: http://i.stack.imgur.com/iaRdO.png


共 (1) 个答案

  1. # 1 楼答案

    您不能在ui线程中长时间或后台运行进程,因此请尝试使用AsyncTask连接xmpp服务器:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvHello = (TextView) findViewById(R.id.tvHello);
        Log.i("ohyeah", "I'm here");
        connectToXmppServer();
     }
    
    public void connectToXmppServer(){
        new AsyncTask<Void,Void,String>(){
           @Override
           protected String doInBackground(Void... params) {
               config = new ConnectionConfiguration("host", 5222, "servername");
               connection = new XMPPTCPConnection(config);
               try {
                   connection.connect();
                   // tvHello.setText("Connected to XMPP server");
                   Log.i("ohyeah", "Successfully Connected");
               } catch (XMPPException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   Log.e("ohyeah", "Not Connected");
               } catch (SmackException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   Log.i("ohyeah", "Something Fishy");
               } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
                   Log.i("ohyeah", "yes");
               }
               return null;
            }
       }.execute();
    }