我知道我必須使用線程才能在Android應用程序中使用Internet,但我不知道如何編寫它。 我有一個類叫「JabberSmackAPI」 - 在這個類我有登錄,通過XMPP發送和接收功能。Android應用程序中的網絡和線程
而我的應用程序中有一個按鈕,當我按下按鈕時它應該登錄到googleTalk帳戶。
這對Java項目(我可以登錄和發送消息)很好,但不適用於Android應用程序項目。 我收到此錯誤:「android.os.NetworkOnMainThreadException」。
我的班級:
public class JabberSmackAPI
{
XMPPConnection connection;
public void login(String userName, String password) throws XMPPException
{
ConnectionConfiguration config = new ConnectionConfiguration("talk.google.com",5222,"gmail.com");
connection = new XMPPConnection(config);
connection.connect();
SASLAuthentication.supportSASLMechanism("PLAIN", 0);
connection.login("email", "password");
}
public void sendMessage(String message, String to) throws XMPPException
{
Message msg = new Message(to, Message.Type.chat);
msg.setBody(message);
connection.sendPacket(msg);
listeningForMessages();
}
public void disconnect()
{
connection.disconnect();
}
public void listeningForMessages() {
PacketFilter filter = new AndFilter(new PacketTypeFilter(Message.class));
PacketCollector collector = connection.createPacketCollector(filter);
while (true) {
Packet packet = collector.nextResult();
if (packet instanceof Message) {
Message message = (Message) packet;
if (message != null && message.getBody() != null)
System.out.println("Received message from "
+ packet.getFrom() + " : "
+ (message != null ? message.getBody() : "NULL"));
}
}
}
我的應用程序的代碼是:
public class MainActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1=(Button)findViewById(R.id.button1);
btn1.setOnClickListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v) {
if(v.getId()==R.id.button1)
{
try{
Toast.makeText(this, "T", Toast.LENGTH_LONG).show();
JabberSmackAPI c = new JabberSmackAPI();
c.login("username", "password");
}
catch(Exception e)
{
Log.e("Error","Error in code:"+e.toString());
e.printStackTrace();
}
}
}
}
我試圖在網絡操作,但沒有奏效。我不知道什麼代碼(來自我的代碼)應該在「AsyncTask」下面,以及「onPostExecute」下的代碼是什麼等等。 –
Zdev
2013-03-12 15:01:29
嗯,現在我更仔細地閱讀你的代碼,你想要一個持續的連接運行。這不適用於AsyncTasks - 它們僅適用於有限的請求(連接結束後onPostExecute觸發)。您將需要爲此啓動一個新線程。你將不得不閱讀http://developer.android.com/guide/faq/commontasks.html#threading。 – Shade 2013-03-12 15:08:04
查看我的更新答案,但這不是線程教程的地方。 – Shade 2013-03-12 15:10:56