1/ Create A Class MyReceiver class and extends BroadcastReceiver Check Internet Connectivity
package com.tutorialb.androideample;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
boolean isConnected = netInfo != null && netInfo.isConnected();
if (isConnected) {
Toast.makeText(context, "Internet connected", Toast.LENGTH_SHORT).show();
Log.i("NetworkChangeReceiver", "Internet connected");
} else {
Toast.makeText(context, "No internet connection", Toast.LENGTH_SHORT).show();
Log.i("NetworkChangeReceiver", "No internet connection");
}
}
}
package com.tutorialb.androideample;
import androidx.appcompat.app.AppCompatActivity;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
MyReceiver myReceiver = new MyReceiver();
IntentFilter intentFilter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter=new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(myReceiver, intentFilter);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(myReceiver);
}
}
3/ Then Change AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AndroidEample">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="MyReceiver"
android:exported="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>
</manifest>