Abdullah
Abdullah

Reputation: 63

Android - Checking internet connection before starting an intent

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.

Upvotes: 1

Views: 687

Answers (4)

Wajid khan
Wajid khan

Reputation: 872

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.

Upvotes: 0

sherin
sherin

Reputation: 1091

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" /> 

Upvotes: 1

Shine
Shine

Reputation: 3818

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

Upvotes: 0

nobalG
nobalG

Reputation: 4630

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" />

Upvotes: 0

Related Questions