We’ve developed a demo Android chat room application using AppWarp which illustrates how to handle intermittent network connection errors. It uses AppWarp’s network resiliency APIs.
Why is Network Resiliency required: On mobile devices, data connectivity has always been an issue. While users are on the go, the data source will often switch towers or downgrade/upgrade between 2G and 3G or WiFi or app goes to background by screen lock or by pressing home button. This has an impact on applications/games that rely on persistent data connectivity. AppWarp also provides powerful feature for handling network resiliency by which a user can maintain its app’s previous state in case of loosing connectivity.
Como gestionar problemas de conexión en dispositivos Android mientras está desarrollando Juegos Multijugador – AppWarp
Hemos desarrollado un demo de la aplicación Android chat room usando AppWarp el cual ilustra cómo gestionar errores de conexión de redes intermitentes. Esto usa la red de Appwarp resistencia APIs.
To know more about AppWarp Resiliency : click Here
Application Contains Two Activities
MainActivity:
Main Activity allows user to connect to the AppWarp Server. Users enter their name and connect to the AppWarp Server. To enable the Resiliency Feature, you need to set the Recovery Allowance interval after initializing WarpClient:
private void init(){
WarpClient.initialize(Constants.apiKey, Constants.secretKey);
WarpClient.setRecoveryAllowance(120);
try {
theClient = WarpClient.getInstance();
} catch (Exception ex) {
Toast.makeText(this, "Exception in Initilization", Toast.LENGTH_LONG).show();
}
}
This tells the server to set the recovery allowance to the specified time during which the server will not destroy the user session even in case of loss of connectivity.
We have created a static room using AppHq console. Once connected and subscribed to the room, we move to the ChatActivity.
public static final String roomId = "1469583531"; // static room id defined in Constant.java
@Override
public void onSubscribeRoomDone(RoomEvent event) {
if(event.getResult()==WarpResponseResultCode.SUCCESS){
Intent intent = new Intent(this, ChatActivity.class);
startActivity(intent);
}else{
showToastOnUIThread("onSubscribeRoomDone Failed with ErrorCode: "+event.getResult());
}
}
ChatActivity.java
This Activity contains the logic of sending/receiving chat and maintains chat log. The upper part contains a list of joined users in the same room. Green Indicator means the user is online and grey means paused (temporary connection error).
Lower part of screen contains chat log send by users.
With the starting of this activity, we retrieve online users of room by calling
theClient.getLiveRoomInfo(Constants.roomId);
with the response in onGetLiveRoomInfoDone we add joined user in users list adapter.
public void onGetLiveRoomInfoDone(final LiveRoomInfoEvent event) {
if(event.getResult()==WarpResponseResultCode.SUCCESS){
onlineUserList.clear();
if(event.getJoinedUsers().length>1){// if more than one user is online
final String onlineUser[] = Utils.removeLocalUserNameFromArray(event.getJoinedUsers());
for(int i=0;i
Handing Connection Resiliency:
In case if any user breaks connectivity to AppWarp server by any reason, server will maintain the session until the defined recovery time but it will send a notification to the other users in the room that given user is in a paused state.
If user recovers its connection in the defined Resiliency time then the other users get notification that user has resumed. Otherwise the users will get the OnUserLeftRoom notification and remove the user from OnlineUser List.
Maintain Pause/Resume State: If we are using AppWarp Resiliency Feature we will get a notification if any user breaks connection to AppWarp server.
@Override
public void onUserPaused(String locid, boolean isLobby, String userName) {
for(int i=0;i
Recover Connection:
If user's internet connection is broken by some reasons like switch over 2G/3G/WiFi/towers or by any other reason, we get a connection Error in ConnectonRequestListener with error code WarpResponseResultCode.CONNECTION_ERROR_RECOVERABLE by this we call recover connection API to resume our previous session. We recommend retrying to recover the connection at an interval of 5 seconds.
theClient.RecoverConnection();
@Override
public void onConnectDone(final ConnectEvent event) {
if(event.getResult() == WarpResponseResultCode.SUCCESS){
showToastOnUIThread("Connection success");
}
else if(event.getResult() == WarpResponseResultCode.SUCCESS_RECOVERED){
showToastOnUIThread("Connection recovered");
runOnUiThread(new Runnable() {
@Override
public void run() {
if(progressDialog!=null){
progressDialog.dismiss();
}
progressDialog = ProgressDialog.show(ChatActivity.this, "", "Please wait..");
}
});
theClient.getLiveRoomInfo(Constants.roomId);
}
else if(event.getResult() == WarpResponseResultCode.CONNECTION_ERROR_RECOVERABLE){
runOnUiThread(new Runnable() {
@Override
public void run() {
progressDialog = ProgressDialog.show(ChatActivity.this, "", "Recoverable connection error. Recovering session after 5 seconds");
}
});
handler.postDelayed(new Runnable() {
@Override
public void run() {
progressDialog.setMessage("Recovering...");
theClient.RecoverConnection();
}
}, 5000);
}
else{
showToastOnUIThread("Non-recoverable connection error."+event.getResult());
handleLeaveRoom();
this.finish();
}
}
Source Code can be downloaded or viewed from our git repo. If you have any questions or need any further assistance, please feel free to write us at support@shephertz.com.
Por qué se requiere Network Resiliency: En dispositivos móviles, conectividad de datos ha sido siempre un problema. Mientras los usuarios se están moviendo, la fuente de datos a menudo cambiará de torre o se degradará/actualizará entre 2G y 3G o WiFi o la aplicación se va a un segundo plano cuando se bloque la pantalla o si se presiona el botón de inicio. Esto tiene un impacto en aplicaciones/juegos que se basan en la conectividad de datos persistentes. AppWarp también suministra una función poderosa para gestionar la resiliencia de red por la cual un usuario puede mantener el estado anterior de su aplicación en caso de perder conectividad.
Para saber más acerca de Resiliencia de AppWarp: Click aquí
La aplicación contiene dos actividades
Actividad Principal:
La actividad principal permite al usuario conectarse con el servidor de AppWarp. El usuario ingresa su nombre y se conecta al servidor AppWarp. Para activar la Función de Resiliencia, necesita establecer el intervalo Recovery Allowance después de iniciar WarpClient:
private void init(){
WarpClient.initialize(Constants.apiKey, Constants.secretKey);
WarpClient.setRecoveryAllowance(120);
try {
theClient = WarpClient.getInstance();
} catch (Exception ex) {
Toast.makeText(this, "Exception in Initilization", Toast.LENGTH_LONG).show();
}
}
Esto le dice al servidor que establezca el Recovery Allowance por un tiempo específico durante el cual el servidor no destruirá la sección de usuario, incluso en caso de pérdida de conectividad.
Hemos creado una sala estática usando AppHq console. Una vez conectado y suscrito a la sala, nos trasladamos a ChatActivity.
public static final String roomId = "1469583531"; // static room id defined in Constant.java
@Override
public void onSubscribeRoomDone(RoomEvent event) {
if(event.getResult()==WarpResponseResultCode.SUCCESS){
Intent intent = new Intent(this, ChatActivity.class);
startActivity(intent);
}else{
showToastOnUIThread("onSubscribeRoomDone Failed with ErrorCode: "+event.getResult());
}
}
ChatActivity.java
Esta actividad contiene la lógica de enviar/recibir chat y mantiene el registro de chat. La parte de arriba contiene una lista de usuarios registrados en la misma sala. El indicador verde significa que el usuario está en línea y el gris significa que esta pausado (error de conexión temporal).
La parte baja de la pantalla contiene el registro al chat enviado por los usuarios.
Con la respuesta en onGetLiveRoomInfoDone agregamos usuarios registrados en adaptador de lista de usuarios
theClient.getLiveRoomInfo(Constants.roomId);
with the response in onGetLiveRoomInfoDone we add joined user in users list adapter.
public void onGetLiveRoomInfoDone(final LiveRoomInfoEvent event) {
if(event.getResult()==WarpResponseResultCode.SUCCESS){
onlineUserList.clear();
if(event.getJoinedUsers().length>1){// if more than one user is online
final String onlineUser[] = Utils.removeLocalUserNameFromArray(event.getJoinedUsers());
for(int i=0;i
Gestionando Resiliencia de Conexión:
En caso de que algún usuario pierda conectividad al servidor AppWarp por alguna razón, el servidor mantendrá la sección hasta el tiempo de recuperación definitiva, pero enviará una notificación a los usuarios en la sala que dicho usuario está en estado de pausa.
Si el usuario recupera la conexión en el tiempo de resiliencia definido, entonces los otros usuarios reciben una notificación que dicho usuario ha reanudado. De lo contrario, los usuarios recibirán la notificación OnUserLeftRoom y el usuario será eliminado de la lista de OnlineUser.
Mantener el estado Pausa/Reanudar: si estamos usando AppWarp Resiliency Feature obtendremos una notificación si algún usuario pierde conexión con el servidor AppWarp.
@Override
public void onUserPaused(String locid, boolean isLobby, String userName) {
for(int i=0;i
Conexión Recuperada
Si un usuario pierde la conexión a internet por algún motivo como el cambio de canal de 2G/3G/WiFi/torre o por algún otro motivo, obtendremos una conexión de Error en ConnectonRequestListener con error de codificación WarpResponseResultCode.CONNECTION_ERROR_RECOVERABLE para esto llamamos API recuperador de conexión para reanudar nuestra conexión previa. Recomendamos reintentar recuperar la conexión en un intervalo de 5 minutos.
theClient.RecoverConnection();
@Override
public void onConnectDone(final ConnectEvent event) {
if(event.getResult() == WarpResponseResultCode.SUCCESS){
showToastOnUIThread("Connection success");
}
else if(event.getResult() == WarpResponseResultCode.SUCCESS_RECOVERED){
showToastOnUIThread("Connection recovered");
runOnUiThread(new Runnable() {
@Override
public void run() {
if(progressDialog!=null){
progressDialog.dismiss();
}
progressDialog = ProgressDialog.show(ChatActivity.this, "", "Please wait..");
}
});
theClient.getLiveRoomInfo(Constants.roomId);
}
else if(event.getResult() == WarpResponseResultCode.CONNECTION_ERROR_RECOVERABLE){
runOnUiThread(new Runnable() {
@Override
public void run() {
progressDialog = ProgressDialog.show(ChatActivity.this, "", "Recoverable connection error. Recovering session after 5 seconds");
}
});
handler.postDelayed(new Runnable() {
@Override
public void run() {
progressDialog.setMessage("Recovering...");
theClient.RecoverConnection();
}
}, 5000);
}
else{
showToastOnUIThread("Non-recoverable connection error."+event.getResult());
handleLeaveRoom();
this.finish();
}
}
Código de Fuente puede ser descargado o visto desde nuestro git repo. Si tiene alguna pregunta o necesita asistencia, por favor contáctenos a support@shephertz.com.
Leave A Reply