Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android check Internet connection automatically

Hello world how to always detect if I am connected or disconnected from the Internet automatically. Example: When I connected and I turn off 3G or wifi the toast says I'm disconnected, 3 seconds after I activate the 3G or wifi and a toast tells me I am connected.

I use this method but it tells me the state of the connection at startup of the application but not during navigation in the application.

 ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

//For 3G check
    boolean is3g = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
            .isConnectedOrConnecting();
//For WiFi Check
    boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
            .isConnectedOrConnecting();


    if (!is3g && !isWifi)
    {
        Toast.makeText(getApplicationContext(),"Network Connection is OFF", Toast.LENGTH_LONG).show();
    }
    else
    {
        Toast.makeText(getApplicationContext(),"Network Connection is ON", Toast.LENGTH_LONG).show();

    }

Help me please

like image 872
slama007 Avatar asked Feb 09 '23 19:02

slama007


2 Answers

You can use a utility class and BroadcastReceiver for this purpose. Below link shows show step by step procedure

http://viralpatel.net/blogs/android-internet-connection-status-network-change/

like image 84
Zahan Safallwa Avatar answered Feb 11 '23 15:02

Zahan Safallwa


You could use Timer's schedule to run a thread. Notice the last 3000 which will make it run every 3 seconds.

Timer timer = new Timer();
timer.schedule(new TimerTask()
{
    @Override
    public void run()
    {
        ConnectivityManager manager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

        //For 3G check
        boolean is3g = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
            .isConnectedOrConnecting();
        //For WiFi Check
        boolean isWifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
            .isConnectedOrConnecting();


        if (!is3g && !isWifi)
        {
            Toast.makeText(getApplicationContext(),"Network Connection is OFF", Toast.LENGTH_LONG).show();
        }
        else
        {
            Toast.makeText(getApplicationContext(),"Network Connection is ON", Toast.LENGTH_LONG).show();

        }
    }
}, 0, 3000);
like image 43
Smittey Avatar answered Feb 11 '23 14:02

Smittey