How to check internet connection in android?

AndroidProgrammingMobile Development

This example demonstrate about how to check the state of internet connection through broadcast Receiver.

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − To find the internet status we have to add network state permission to AndroidManifest.xml file as shown below.

<?xml version="1.0" encoding = "utf-8"?>
<manifest xmlns:android = "http://schemas.android.com/apk/res/android"
   package = "com.example.andy.myapplication">
   <uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
   <application
      android:allowBackup = "true"
      android:icon = "@mipmap/ic_launcher"
      android:label = "@string/app_name"
      android:roundIcon = "@mipmap/ic_launcher_round"
      android:supportsRtl = "true"
      android:theme = "@style/AppTheme">
      <activity android:name = ".MainActivity">
         <intent-filter>
            <action android:name = "android.intent.action.MAIN" />
            <category android:name = "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
   </application>
<manifest>

Step 3 − Following is the content of the modified main activity file MainActivity.java. This file can include each of the fundamental life cycle methods. We have created a text view, when use click on text view it going to call broadcastIntent() method to broadcast a CONNECTIVITY_ACTION intent.

import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   private BroadcastReceiver MyReceiver = null;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      MyReceiver = new MyReceiver();
      TextView click=findViewById(R.id.click);
      click.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            broadcastIntent();
         }
      });
   }
   public void broadcastIntent() {
      registerReceiver(MyReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
   }
   @Override
   protected void onPause() {
      super.onPause();
      unregisterReceiver(MyReceiver);
   }
}

Step 4 − Create a NetworkUtil class to find the net work status as show below.

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
class NetworkUtil {
   public static String getConnectivityStatusString(Context context) {
      String status = null;
      ConnectivityManager cm = (ConnectivityManager)           context.getSystemService(Context.CONNECTIVITY_SERVICE);
     NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
      if (activeNetwork != null) {
         if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
            status = "Wifi enabled";
            return status;
         } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
            status = "Mobile data enabled";
            return status;
         }
      } else {
    status = "No internet is available";
      return status;
    }
    return status;
   }
}

Step 5 −Create a broadcast receiver class and named as MyReceiver.java .This broadcast receiver going to update the ui from NetworkUtil class.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
   @Override
   public void onReceive(Context context, Intent intent) {
      String status = NetworkUtil.getConnectivityStatusString(context);
      if(status.isEmpty()) {
         status="No Internet Connection";
      }
      Toast.makeText(context, status, Toast.LENGTH_LONG).show();
   }
}

Step 6 −Update your broadcast receiver in manifest file as shown below.

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package = "com.example.andy.myapplication">
   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
   <application
      android:allowBackup="true"
      android:icon = "@mipmap/ic_launcher"
      android:label = "@string/app_name"
      android:roundIcon = "@mipmap/ic_launcher_round"
      android:supportsRtl = "true"
      android:theme = "@style/AppTheme">
   <activity android:name = ".MainActivity>
      <intent-filter>
         <action android:name = "android.intent.action.MAIN" />
         <category android:name = "android.intent.category.LAUNCHER" />
      </intent-filter>
   </activity>
      <receiver android:name = "MyReceiver">
         <intent-filter>
            <action android:name = "android.net.conn.CONNECTIVITY_CHANGE" />
            <action android:name = "android.net.wifi.WIFI_STATE_CHANGED" />
         </intent-filter>
      </receiver>
   </application>
</manifest>

Step 7 −Following will be the content of res/layout/activity_main.xml file to include a textview to broadcast connectivity state intent.

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity">
<TextView
   android:id="@+id/click"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Click here"
   app:layout_constraintBottom_toBottomOf="parent"
   app:layout_constraintLeft_toLeftOf="parent"
   app:layout_constraintRight_toRightOf="parent"
   app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>

Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run Play  icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen.

The above screen we have selected wifi connection and the output should be like this −

Default Screen

The above screen we have selected wifi connection and the output should be like this −

Wifi Enabled

Mobile Data Enabled

No Internet

Click here to download the project code

raja
Published on 03-Dec-2018 12:28:28
Advertisements