我知道我必须使用线程才能在 Android 应用程序中使用互联网,但我不知道如何编写它。我有一个类叫做“JabberSmackAPI”——在这个类上我有登录,通过 XMPP 发送和接收功能。
我的应用程序上有一个按钮,当我按下按钮时,它应该登录到 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();
}
}
}
}