据我们所知,我们无法在 UI 线程中执行 web 连接,并尝试在 Thread 或 AsyncTask 上执行,而我选择在可运行的 Thread 中运行 web 连接。当我单击按钮时,日志显示正确的代码connection.connect();
恰好是 NetworkOnMainThreadException,但是你知道,从我下面的代码中,我已经在线程中编写了我的 networkconnecton 代码,所以,任何人都告诉我处理这个问题的正确方法问题?
public class MainActivity extends Activity {
private Button btn_send;
private EditText et_content;
private Connection connection;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_send = (Button) findViewById(R.id.bt_sendms);
et_content = (EditText) findViewById(R.id.et_inputcontent);
btn_send.setOnClickListener(onClicListener);
}
public OnClickListener onClicListener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
handler.post(task);
}
};
private Handler handler = new Handler();
private Runnable task = new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
XMPPConnection.DEBUG_ENABLED = true;
ConnectionConfiguration connectionConfig = new ConnectionConfiguration(
"192.168.1.108", Integer.parseInt("5222"), "dell-PC");
AccountManager accountManager;
connectionConfig.setReconnectionAllowed(true);
connectionConfig.setSendPresence(true);
connection = new XMPPConnection(connectionConfig);
try {
connection.connect();
accountManager = connection.getAccountManager(); //
connection.login("admin", "888889");
ChatManager chatManager = connection.getChatManager();
Chat newChat = chatManager.createChat("bryanwu@qq.com",
new MessageListener() {
@Override
public void processMessage(Chat chat,
Message message) {
}
});
try {
newChat.sendMessage(et_content.getText().toString());
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
et_content.setText("");
} catch (XMPPException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //
}
};
}