Check connection at any time [duplicate]

2

It's the following, I'm creating app that depends on the internet connection for most services. To make it more dynamic, I thought I'd do something like the YouTube app. In the youtube app it warns you almost instantly that the application is offline. See:

IgaveageneralsearchandtriedtouseThreadsintwoways:

1.Executor+Runnable

classThreadInfinityimplementsExecutor{@Overridepublicvoidexecute(@NonNullRunnabler){while(true){r.run();}}}Threadr=newThread(newRunnable(){@Overridepublicvoidrun(){if(manager.getActiveNetworkInfo()!=null&&manager.getActiveNetworkInfo().isConnectedOrConnecting()){Toast.makeText(getApplicationContext(),"Você está conectado", Toast.LENGTH_SHORT);

                    } else {

                         Toast.makeText(getApplicationContext(), "Você está desconectado", Toast.LENGTH_SHORT);

                    }

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });

        ThreadInfinity t = new ThreadInfinity();
        t.execute(r);

2. AsyncTask

        Context context = getApplicationContext();
        final ConnectivityManager manager = (ConnectivityManager) context.getSystemService(context.CONNECTIVITY_SERVICE);

        class TheadInfinity extends AsyncTask<Void, Void, Void> {
            protected Void doInBackground(Void... params) {
                while (true)
                    try {
                        if (manager.getActiveNetworkInfo() != null && manager.getActiveNetworkInfo().isConnectedOrConnecting()) {

                             Toast.makeText(getApplicationContext(), "Você está conectado", Toast.LENGTH_SHORT);

                        } else {

                             Toast.makeText(getApplicationContext(), "Você está desconectado", Toast.LENGTH_SHORT);

                        }
                        Thread.sleep(1000);

                    } catch (Exception e) {
                        Toast.makeText(getApplicationContext(), "Erro", Toast.LENGTH_SHORT);
                    }
            }
        }

        TheadInfinity t = new TheadInfinity();
        t.doInBackground();

Both do not crash the app but the screen goes blank. So:

IthinkthecorrectmodeisnotwithThread.Theremustbesomelistenerthatcanbeused.ButIfoundnowhere"on the internet".

Doubt

How can I do this? =)

    
asked by anonymous 25.04.2018 / 05:00

2 answers

3

I use this class in my projects:

public class ConexaoInternet extends BroadcastReceiver {

    public enum TipoConexao {TIPO_NAO_CONECTADO,TIPO_WIFI, TIPO_MOBILE};

    private  TipoConexao tipoConexaoATUAL = TipoConexao.TIPO_NAO_CONECTADO; //cache
    private boolean inicializou = false;

    private TipoConexao getStatusConexao(Context context) {
        synchronized (tipoConexaoATUAL){
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            tipoConexaoATUAL = TipoConexao.TIPO_NAO_CONECTADO;

            NetworkInfo activeNetwork = cm==null ? null : cm.getActiveNetworkInfo();
            if (null != activeNetwork) {
                if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
                    tipoConexaoATUAL = TipoConexao.TIPO_WIFI;
                }
                if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE){
                    tipoConexaoATUAL = TipoConexao.TIPO_MOBILE;
                }
            }

            return tipoConexaoATUAL;
        }
    }

    public TipoConexao getTipoConexaoAtual(Context context){
        if(!inicializou){
            inicializou = true;
            return getStatusConexao(context);
        }
        return tipoConexaoATUAL;
    }

    public interface IOnMudarEstadoConexao{
        void onMudar(TipoConexao tipoConexao);
    }
    private ArrayList<IOnMudarEstadoConexao> onMudarEstadoConexoesListeners = new ArrayList<>();

    public void addOnMudarEstadoConexao(IOnMudarEstadoConexao t){
        onMudarEstadoConexoesListeners.add(t);
    }
    public void removeOnMudarEstadoConexao(IOnMudarEstadoConexao t){
        onMudarEstadoConexoesListeners.remove(t);
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        TipoConexao tipo = getStatusConexao(context);

        for(IOnMudarEstadoConexao o : onMudarEstadoConexoesListeners){
            o.onMudar(tipo);
        }

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if(connectivityManager!=null){
                for (Network net : connectivityManager.getAllNetworks()) {
                    NetworkInfo networkInfo = connectivityManager.getNetworkInfo(net);
                    if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        connectivityManager.bindProcessToNetwork(net);
                        break;
                    }
                }
            }
        }
    }
}

You need to register when the Activity is created

private ConexaoInternet conexaoInternet;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
    intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
    conexaoInternet = new ConexaoInternet();
    registerReceiver(conexaoInternet,intentFilter);

Removed when activity is destroyed

@Override
protected void onDestroy() {
    super.onDestroy();
    unregisterReceiver(conexaoInternet);
}

Example: To add a listener every time the device changes its connection

conexaoInternet.addOnMudarEstadoConexao(
    new ConexaoInternet.IOnMudarEstadoConexao() {
        @Override
        public void onMudar(ConexaoInternet.TipoConexao tipoConexao) {
            if(tipoConexao == ConexaoInternet.TipoConexao.TIPO_MOBILE ||
                            tipoConexao == ConexaoInternet.TipoConexao.TIPO_WIFI){

                //faça algo quando a conexão for alterada para 3g/wifi

            }else if(tipoConexao == ConexaoInternet.TipoConexao.TIPO_NAO_CONECTADO){

               //faça algo quando o dispositivo perder conexão

            }
        }
    }
);
    
25.04.2018 / 05:31
1

First you need to map an action in AndroidManifest.xml:

<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>

Then it will be possible to create a receiver so that you have an action to take when the connection type changes:

public class ConnectionChanged extends BroadcastReceiver {

    private final String ACTION_CONN_CHANGED = "android.net.conn.CONNECTIVITY_CHANGE";

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction() != null && intent.getAction().equals(ACTION_CONN_CHANGED)) {

            //TODO SEU CODIGO
        }
    }
}

And do as @DigaoParceiro said, check the type of connection through a modeling and take a second action for each type of connection.

boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;

More details in the Android documentation: Determining and monitoring connectivity status

    
25.04.2018 / 13:19