BroadcastReceiver
Class in not working at app first startup. I want to check the internet connection simultaneously also at app startup. Please help with the issue.
NetworkchangeListener.Java
public class NetworkChangeListener extends BroadcastReceiver {
public static boolean isNetworkConnected= false ;
@Override
public void onReceive(Context context, Intent intent) {
isNetworkConnected = isNetworkAvailable(context);
if(isNetworkConnected){
Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "Not Connected", Toast.LENGTH_SHORT).show();
}
}
private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null;
}
}
Below is my Manifest.xml File
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dcastalia.clienttest">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_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=".NetworkChangeListener">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
</application>
</manifest>
It's working fine when i change the network state but for the first runtime it's doesn't working.