Primeros pasos con quickblox
Solicitar lista de diálogo de usuario conectado
Código para recibir diálogos de chat del servidor Quickblox del usuario que ha iniciado sesión (Ejemplo con vista de lista)
private void receiveChatList() {
QBRequestGetBuilder requestBuilder = new QBRequestGetBuilder();
requestBuilder.setLimit(100);
QBRestChatService.getChatDialogs(null, requestBuilder).performAsync(
new QBEntityCallback<ArrayList<QBChatDialog>>() {
@Override
public void onSuccess(final ArrayList<QBChatDialog> result, Bundle params) {
int totalEntries = params.getInt("total_entries");
Log.wtf("chat",""+result);
TrumeMsgAdapter adapter=new TrumeMsgAdapter(this,result);
chatlistView.setAdapter(adapter);
chatlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(new Intent(this,ChatingActivity.class).putExtra("dialog",result.get(position)));
}
});
}
@Override
public void onError(QBResponseException responseException) {
}
});
}
Código del adaptador:-
public class TrumeMsgAdapter extends BaseAdapter {
private ArrayList<QBChatDialog> chatlist;
private Context context;
public TrumeMsgAdapter(Context c,ArrayList<QBChatDialog> chatlist){
this.chatlist=chatlist;
this.context=c;
}
@Override
public int getCount() {
return chatlist.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View List;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
List = inflater.inflate(R.layout.trume_msg_adapter, null);
TextView username=(TextView) List.findViewById(R.id.UserName);
TextView lastmessage=(TextView)List.findViewById(R.id.lastmessage);
username.setText(chatlist.get(position).getName());
lastmessage.setText(chatlist.get(position).getLastMessage());
} else {
List = convertView;
TextView username=(TextView) List.findViewById(R.id.UserName);
TextView lastmessage=(TextView)List.findViewById(R.id.lastmessage);
username.setText(chatlist.get(position).getName());
lastmessage.setText(chatlist.get(position).getLastMessage());
}
return List;
}
}
Instalación o Configuración
Instrucciones detalladas sobre cómo configurar o instalar Quickblox.
Vaya a https://admin.quickblox.com y haga clic en “Registrarse” en la parte superior o simplemente siga el enlace: https://admin.quickblox.com/register.
Importar Quickblox Chat Android SDK
Añadir repositorio
repositories {
maven {
url "https://github.com/QuickBlox/quickblox-android-sdk-releases/raw/master/"
}
}
Agregue Project Gradle para la funcionalidad de chat
dependencies {
compile("com.quickblox:quickblox-android-sdk-chat:2.6.1")
}
Agregue Project Gradle para la funcionalidad de video
dependencies {
compile "com.quickblox:quickblox-android-sdk-videochat-webrtc:2.6.1"
}
Preparar el servicio de chat
Para inicializar el uso del servicio de chat:
QBChatService.setDebugEnabled(verdadero); // habilitar el registro de chat
QBChatService.setDefaultPacketReplyTimeout(10000);//establecer respuesta tiempo de espera en milisegundos para el paquete de conexión. Se puede utilizar para eventos como iniciar sesión, unirse al diálogo para aumentar el tiempo de respuesta de espera del servidor si la red es lenta.
Para configurar el socket de chat, use QBChatService.ConfigurationBuilder;
QBChatService.ConfigurationBuilder chatServiceConfigurationBuilder = new QBChatService.ConfigurationBuilder();
chatServiceConfigurationBuilder.setSocketTimeout(60); //Sets chat socket's read timeout in seconds
chatServiceConfigurationBuilder.setKeepAlive(true); //Sets connection socket's keepAlive option.
chatServiceConfigurationBuilder.setUseTls(true); //Sets the TLS security mode used when making the connection. By default TLS is disabled.
QBChatService.setConfigurationBuilder(chatServiceConfigurationBuilder);
Iniciar sesión para chatear
Cree una sesión con el usuario e inicie sesión en QuickBlox Chat
// Initialise Chat service
QBChatService chatService = QBChatService.getInstance();
final QBUser user = new QBUser("garrysantos", "garrysantospass");
QBAuth.createSession(user, new QBEntityCallback<QBSession>() {
@Override
public void onSuccess(QBSession session, Bundle params) {
// success, login to chat
user.setId(session.getUserId());
chatService.login(qbUser, new QBEntityCallback() {
@Override
public void onSuccess() {
}
@Override
public void onError(QBResponseException errors) {
}
});
}
@Override
public void onError(QBResponseException errors) {
}
});
Para manejar diferentes estados de conexión, use ConnectionListener:
ConnectionListener connectionListener = new ConnectionListener() {
@Override
public void connected(XMPPConnection connection) {
}
@Override
public void authenticated(XMPPConnection connection) {
}
@Override
public void connectionClosed() {
}
@Override
public void connectionClosedOnError(Exception e) {
// connection closed on error. It will be established soon
}
@Override
public void reconnectingIn(int seconds) {
}
@Override
public void reconnectionSuccessful() {
}
@Override
public void reconnectionFailed(Exception e) {
}
};
QBChatService.getInstance().addConnectionListener(connectionListener);
Crear nuevo cuadro de diálogo de chat (privado)
QBChatDialog dialog = DialogUtils.buildPrivateDialog("USER_ID of other user");
QBRestChatService.createChatDialog(dialog).performAsync(new QBEntityCallback<QBChatDialog>() {
@Override
public void onSuccess(QBChatDialog result, Bundle params) {
//if dialog created successfully
//result param return all details about that dialog
}
@Override
public void onError(QBResponseException responseException) {
//error creating dialog
}
});