Android的线程管理
问题描述:
我连接XMPP服务器使用线程,但我很好奇一个的事儿。我这个代码onResume
方法连接:Android的线程管理
Thread t=new Thread(new Runnable() {
@Override
public void run() {
ConnectionConfiguration connConfig=new ConnectionConfiguration("SERVER IP", 5222,"localhost");
XMPPConnection connection=new XMPPTCPConnection(connConfig);
connection.connect();
}
});
t.start();
然后,如果用户暂停该应用程序我与此断开在
Thread t=new Thread(new Runnable() {
@Override
public void run() {
connection.disconnect();
}
});
t.start();
所以代码,我在每个家庭按钮press.Is创建新线程这是一个很好的方法吗?我不知道这是否会导致内存泄漏?你对这个操作有什么建议?
答
我做了类似的事情,而不是XMPP,但套接字和它的工作。您应该为XMPPConnection创建一个Static类,以确保您始终只使用一个(且相同)连接。当使用套接字时,我发现有时候我的连接在对象上是关闭的,但在网络层仍然有效,并且我有双重消息(同时有两个连接)。
public class XMPPChatSingleton {
public static XMPPChatSingleton instance;
private XMPPConnection xmpp;
private Activity activity;
ProgressDialog pdialog;
int timeOut;
public static XMPPChatSingleton getInstance(Activity activity, boolean reconnect) {
if (instance == null || reconnect) {
instance = getSync(activity, event);
}
return instance;
}
public static synchronized XMPPChatSingleton getSync(Activity activity, Event event) {
instance = new XMPPChatSingleton (activity, event);
return instance;
}
public XMPPConnection getSocket() {
return this.socket;
}
private XMPPChatSingleton (Activity activity, Event event) {
this.activity = activity;
this.context = activity.getApplicationContext();
this.event = event;
this.xmpp = getChatXMPP();
}
private getChatXMPP() {
dialogLoad();
xmpp = new XMPPConnection();
// here you can handle your connection too;
// use timeout to handle reconnection
}
public void disconnect() {
xmpp.disconnect;
}
}
这种方法的优点是您可以在您的所有活动和片段中重复使用相同的连接。你甚至可以创建处理消息发送的方法。通过和适配器来刷新消息到达时,以及所有类型的东西。
我建议你在这里获取从服务器发送的所有数据,并使用context.sendBroadcast(dataYouWantToPass)传递给当前活动活动或片段。
你能举一个小例子吗? – Okan 2015-01-26 19:18:14