【发布时间】:2015-09-07 11:01:17
【问题描述】:
尝试使用 android 中的服务保持 xmpp 连接处于活动状态
public class XMPPService extends Service {
XMPPTCPConnection connection;
String USERNAME;
String PASSWORD;
public XMPPService() {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
onHandleIntent();
return START_STICKY;
}
private void onHandleIntent() {
connection = XMPPClient.getConnection();
connection.addConnectionListener(
new AbstractConnectionListener() {
public void connectionClosed() {
Log.i("connection", "closed");
}
public void connectionClosedOnError(Exception e) {
Log.i("connection", "closed on error");
}
public void reconnectionFailed(Exception e) {
Log.i("reconnection", "failed");
}
public void reconnectionSuccessful() {
if (connection.isAuthenticated()) {
Log.i("isauthenticauted : ", String.valueOf(connection.isAuthenticated()));
Log.i("reconnection", "succesful");
} else {
try {
connection.login(USERNAME, PASSWORD);
} catch (XMPPException e) {
e.printStackTrace();
} catch (SmackException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.i("reconnection", "succesful");
}
}
public void reconnectingIn(int seconds) {
Log.i("reconnectingIn", String.valueOf(seconds));
}
}
);
}
@Override
public void onCreate() {
Log.i("service", "created");
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
当我杀死我的应用程序时,我的服务会重新启动。为什么会这样?当我重新启动时,它给我一个异常 NetworkOnMainThreadException at connection = XMPPClient.getConnection(); 当我杀死我的应用程序时,我不希望我的服务重新启动。
【问题讨论】: