據我們所知,我們不能在UI線程中執行Web連接,並嘗試在Thread或AsyncTask上執行它,並且我選擇在可運行的Thread中運行Web連接。當我點擊按鈕時,日誌顯示connection.connect();
代碼正確的是一個NetworkOnMainThreadException,但是你知道,從我的下面的代碼中,我已經在線程中寫了我的networkconnecton代碼,所以,任何人都告訴我正確的方式來處理這個問題?一個奇怪的NetWorkOnMainThreadException
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("[email protected]",
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();
} //
}
};
}
不要使用'Handler'。它在與UI主線程相同的線程上運行。 http://developer.android.com/reference/android/os/Handler.html – Simon