Android socket.io Activity with AlertDialog. Connection and Disconnection Alert.

You may extend this activity to use in your new activity, you have to implement onDisconnect and onConnect methods, these methods are used to handle connection status changes.

package com.dogukanhan.myapplication.component;

import android.app.AlertDialog;
import android.app.Dialog;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import com.dogukanhan.myapplication.service.PartySocketSingleton;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;

import java.net.URISyntaxException;


public abstract class AppCompatSocketActivity extends AppCompatActivity {

    private static Socket socket;

    private Dialog dialog;

    protected abstract void onConnected();

    protected abstract void onDisconnected();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private Dialog dialog() {
        Dialog dialog = new AlertDialog.Builder(this)
                .setTitle("Connection Failed")
                .setMessage("Tying to connect server, please check your network.")
                .setIcon(android.R.drawable.ic_dialog_alert)
                .create();
        dialog.setCanceledOnTouchOutside(false);
        return dialog;
    }

    private void preConnected() {


        runOnUiThread(() -> {
            this.dialog.hide();
            this.dialog.dismiss();
            this.dialog.cancel();
            this.dialog.closeOptionsMenu();

        });

        socket.on("disconnect", args -> this.preDisconnected());

        this.onConnected();
    }

    private void preDisconnected() {

        runOnUiThread(() -> this.dialog.show());

        socket.on("connect", args -> this.preConnected());

        this.onDisconnected();
    }

    @Override
    protected void onResume() {
        super.onResume();

        this.dialog = dialog();

        if (socket == null) {
            socket = getSocket();
        }

        this.preDisconnected();

        socket.on("connect", args -> this.preConnected());

        socket.connect();
    }

    public static Socket getSocket() {
        if (socket == null) {
            try {
                socket = IO.socket(URL);
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        }
        return socket;
    }

}
Bu yazı Android, Socket.io kategorisine gönderilmiş. Kalıcı bağlantıyı yer imlerinize ekleyin.

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir