1

I want to check the internet connection before opening an intent. How can I do this? I am a beginner in this field. Any help will be appreciated.

Abdullah
  • 63
  • 3
  • possible duplicate of [How do you check the internet connection in android?](http://stackoverflow.com/questions/2326767/how-do-you-check-the-internet-connection-in-android) – Shine Jan 22 '15 at 15:32

4 Answers4

1

This method checks whether mobile is connected to internet and returns true if connected and also you need to update your manifest file

private boolean isNetworkConnected() {

  ConnectivityManager cm = (ConnectivityManager)   getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo networkInfo = cm.getActiveNetworkInfo();
  if (networkInfo == null) {
      // There are no active networks.
      return false;
  } else
  return true;
 }

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
sherin
  • 1,091
  • 2
  • 17
  • 27
0

Try Following code

public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    return netInfo != null && netInfo.isConnectedOrConnecting();
}

Do add permission in the manifest

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
nobalG
  • 4,544
  • 3
  • 34
  • 72
0

Use ConnectivityManager before starting new Intent, if isConnectedOrConnecting() returns true you may proceed with Intent.startActivity()

Don't forget android.permission.ACCESS_NETWORK_STATE in Manifest

Have a look at duplicate here for deeper explanation

Community
  • 1
  • 1
Shine
  • 3,788
  • 1
  • 36
  • 59
0

Very Simple Copy this Function to Your Activity from which you want to Intent.

public boolean CheckInternet() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
                connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
            //we are connected to a network
            return true;
        }
        return false;
    }//end of check int

Now before Intent Simply call this function in if condition

if(CheckInternet()){
Intent intent=new Intent(this,NextActivity.class);
startActivity(intent);
}
else{
Toast.makeText(this, "No Internet.", Toast.LENGTH_SHORT).show();
}

Don't forget to add these lines in AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Thanks.

Wajid khan
  • 842
  • 9
  • 18