我建立了一个基于aSmack的应用程序,很明显,关于连接的所有事情都在服务中运行,因此保持其连接状态非常重要,因为我们知道服务在后台运行,可能会由于电话的低资源而被杀死(通常是Ram ),因此使用服务上的START_STICKY标志,它会以空意图重新启动。
现在我想知道电话上是否没有网络,或者突然之间发生了意外的临时异常(并且由于服务已重新启动,因此尚未设置reconnectionManager),因此必须重新启动应用程序以检索其连接。我的问题是我该如何处理这些例外?我知道我可以做这样的事情:
public void connect(){
try {
connection.connect();
} catch (SmackException | IOException | XMPPException e) {
if(getIntent() == null){
connect();
return;
}
}
}
但这是不专业的imo,我知道有一种确定临时异常的方法,但不幸的是我无法记住或找到它们。任何信息表示赞赏。非常感谢
最佳答案
所以这就是我所做的,可以完美地工作,并且每一件事都算在内。
这是我的服务每次启动时所做的事情
private void connect(){
if (!connection.isConnected()){
try {
connection.connect();
} catch (SmackException | IOException | XMPPException e) {
mainHandler.post(new Runnable() {
@Override
public void run() {
if(intent ==null){
Toast.makeText(getBaseContext(),"Could not Connect to The Server , Network Problems , Retrying in 30 Seconds...", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getBaseContext(),"Could not Connect to The Server , Network Problems...", Toast.LENGTH_LONG).show();
}
}
});
if(intent == null){
//When intent is null, It Means that service got Destroyed middle of app, which
//means user has already connected and Authenticated once, but can not do it again.
//so thats the key
nonMainHandler.postDelayed(new Runnable() {
@Override
public void run() {
connect();
}
},30000);
}
e.printStackTrace();
}
}
try {
if (connection.isConnected() && !connection.isAuthenticated()) {
try {
connection.login(LMApplication.userName,LMApplication.passWord);
} catch (SmackException | IOException | XMPPException e) {
mainHandler.post(new Runnable() {
@Override
public void run() {
if(intent != null){
Toast.makeText(getBaseContext(),"Could not Login Using this Information..", Toast.LENGTH_LONG).show();
}
}
});
e.printStackTrace();
configEnterButton(-1);
}
}
if(connection.isAuthenticated()){
configEnterButton(100);
try {
Thread.sleep(300);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
goAhead();
Log.i("XMPPChatDemoActivity", "Logged in as" + LMApplication.Raw_CurrentUser);
//TODO
// check if need to set presence from shared preferences
Presence p = new Presence(Presence.Type.available,"", 42, Mode.available);
try {
connection.sendPacket(p);
} catch (NotConnectedException e1) {
e1.printStackTrace();
}
}else if(intent == null){
nonMainHandler.post(new Runnable() {
@Override
public void run() {
if(connection.isConnected() && !connection.isAuthenticated()){
try {
connection.login(LMApplication.userName,LMApplication.passWord);
} catch (XMPPException | SmackException
| IOException e) {
e.printStackTrace();
}
}
if(connection.isConnected() && connection.isAuthenticated()){
notifyReconnect();
}else if(connection.isConnected()){
nonMainHandler.postDelayed(this,10000);
}
}});
}