-2

This is not a duplicate

I want to check real-time internet connection from my activity using AsyncTaskand Handler to display or hide TexView if a connection is available or not. But it doesn't work.

My code throws NetworkOnMainThreadException even using AsyncTask

I'm using this code:

class  CheckNetWorkConnection  extends AsyncTask<String, Void,Boolean>{
MyActivity activity;
    public checkNetWorkConnection(MyActivity activity) {
        this.activity= activity;

    }

    @Override
    protected Boolean doInBackground(String... strings) {
        boolean networkAvalaible;

                try {
                    URL myUrl = new URL("https://www.stackoverflow.com");
                    URLConnection connection = myUrl.openConnection();
                    connection.setConnectTimeout(3000);
                    connection.connect();

                    networkAvalaible = true;
                } catch (Exception e) {
                  //I'm catching NetworkInMainThreadException here 
                    e.printStackTrace();
                    networkAvalaible = false;
                }
            }
        });

   // doInBackground always retun false
        return networkAvalaible;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {

    // Using handler to repeat Task


        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (aBoolean){
                    activity.noConnection.setVisibility(View.GONE);
                }else {

                    activity.noConnection.setVisibility(View.VISIBLE);
                }
            }

        },3000);


        super.onPostExecute(aBoolean);
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Constantin N.
  • 2,739
  • 2
  • 16
  • 27
  • 1
    Possible duplicate of [Check for Active internet connection Android](https://stackoverflow.com/questions/17717749/check-for-active-internet-connection-android) – ADM Apr 28 '18 at 08:51
  • `NetworkOnMainThreadException`? Add code how are you calling `CheckNetWorkConnection` . – ADM Apr 28 '18 at 09:13
  • like this `new CheckNetWorkConnection();` – Constantin N. Apr 28 '18 at 09:16
  • Thats can not be the whole statement . Is it `new CheckNetWorkConnection().execute()`? Or `new CheckNetWorkConnection().doInBackground()`? – ADM Apr 28 '18 at 09:17
  • You should use EventBus or BroadCast receiver – Ko Vartthan Apr 28 '18 at 09:18

3 Answers3

0

to use it, you call

new CheckNetWorkConnection().execute(); 

you will want your async task to run indefinitely until an internet connection is lost. your current code will only check one time.

you need to change your codes to be polling for it to work.

@Override
protected Boolean doInBackground(String... strings) {
    boolean networkAvalaible = false;

    do {
            try {
                URL myUrl = new URL("https://www.stackoverflow.com");
                URLConnection connection = myUrl.openConnection();
                connection.setConnectTimeout(3000);
                connection.connect();

                networkAvalaible = true;

                sleep(5000); //check connection every 5 seconds.

// you can call publish progress here to tell your process that 
// connection is available

            } catch (Exception e) {
              //I'm catching NetworkInMainThreadException here 
                e.printStackTrace();
                networkAvalaible = false;
            }
     } while (networkAvalaible); 

//you only exit and asyncTask when connection is lost.


    return networkAvalaible;
}

AsyncTask is not the right way to do it though... take a look at the following article below. https://www.grokkingandroid.com/android-getting-notified-of-connectivity-changes/

Angel Koh
  • 12,479
  • 7
  • 64
  • 91
0

Put this Class into your util Package to chack internet connection anywhere into your project.

ConnectionDetector.java

package util;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

/**
 * Created by Pranav on 29/08/16.
 */
public class ConnectionDetector {
    private Context _context;

    public ConnectionDetector(Context context) {
        this._context = context;
    }

    public boolean isConnectingToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
        }
        return false;
    }
}

Here is a code snippet if MainActivity.java to check internet connection and if internet connection is on then call asynctask otherwise give toast message.

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;

import java.net.URL;
import java.net.URLConnection;

import util.ConnectionDetector;

/**
 * Created by Pranav on 29/08/16.
 */


public class CaseDetaiksActivity extends Activity {

    public static Context context;
    ConnectionDetector mConnectionDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        mConnectionDetector = new ConnectionDetector(context);
        setContentView(R.layout.activity_mail);

        if (mConnectionDetector.isConnectingToInternet()) {
            MyAyncTask MyTask = new MyAyncTask();
            MyTask.execute();
        } else {
            Toast.makeText(context, getString(R.string.please_check_internet), Toast.LENGTH_SHORT).show();
        }
    }

    public static class MyAyncTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
        }

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
            // You can track you progress update here
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                URL myUrl = new URL("https://www.stackoverflow.com");
                URLConnection connection = myUrl.openConnection();
                connection.setConnectTimeout(3000);
                connection.connect();

            } catch (Exception e) {
                //I'm catching NetworkInMainThreadException here
                e.printStackTrace();
            }
            return null;
        }
    }
}

Hope this helps you

InsaneCat
  • 2,115
  • 5
  • 21
  • 40
0
  1. a .Create a broadcast receiver class

      public class NetworkChangeReceiver extends BroadcastReceiver {
    
      @Override
      public void onReceive(final Context context, final Intent intent) {
    
      if(checkInternet(context)){
        Toast.makeText(context, "Network Available Do operations",Toast.LENGTH_LONG).show(); 
        }
      }
    
     public boolean checkInternet(Context context) {
        ServiceManager serviceManager = new ServiceManager(context);
        if (serviceManager.isNetworkAvailable()) {
        return true;
        } else {
        return false;
         }
       }
     }    
    

    b. Create a Service manager class

    public class ServiceManager {
      Context context;
    
      public ServiceManager(Context base) {
          context = base;
       }
    
      public boolean isNetworkAvailable() {
          ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
          NetworkInfo networkInfo = cm.getActiveNetworkInfo();
          return networkInfo != null && networkInfo.isConnected();  
     }
    }
    
  2. Register permissions in the Android Manifest

     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
     <uses-permission android:name="android.permission.INTERNET" />
    
  3. Declare Broadcast Receiver in the Android Manifest

      <receiver android:name=".receivers.NetworkChangeReceiver">
          <intent-filter>
              <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
          </intent-filter>
      </receiver>
    
  4. In your activity :

    a. register your broadcast receiver in onResume()

        registerReceiver(new NetworkChangeReceiver() , new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    

    b. unregister your broadcast receiver in onPause();

        unregisterReceiver(new NetworkChangeReceiver());
    
Ko Vartthan
  • 434
  • 1
  • 4
  • 22
  • I want to check internet access not network connectivity.this will only tell me if device is connected to a network not if device has internet access – Constantin N. Apr 28 '18 at 10:22
  • In activity u need to check the network connectivity in real time when u turned on or off ?? – Ko Vartthan Apr 28 '18 at 11:52
  • `CONNECTIVITY_CHANGE` means not network connectivity .. it is internet connectivity refer this link [Click Here](https://developer.android.com/reference/android/net/ConnectivityManager) – Ko Vartthan Apr 28 '18 at 12:31