Android internet connectivity check.
AndroidManifest.xml parmison;-
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Context.this code
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo!=null && networkInfo.isConnected()){
Toast.makeText(this, "Network On ", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Network Off ", Toast.LENGTH_SHORT).show();
}
advanced Code
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// First Toast
Toast.makeText(this, "Network On", Toast.LENGTH_SHORT).show();
// Now check for slow internet (basic check using thread)
new Thread(new Runnable() {
@Override
public void run() {
try {
long startTime = System.currentTimeMillis();
// Lightweight request
URL url = new URL("https://www.google.com/generate_204");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(3000); // 3 seconds
connection.connect();
long endTime = System.currentTimeMillis();
long responseTime = endTime - startTime;
if (responseTime > 2000) { // 2 seconds threshold
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Slow Internet Connection", Toast.LENGTH_LONG).show();
}
});
}
connection.disconnect();
} catch (Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(), "Internet may be slow or unstable", Toast.LENGTH_LONG).show();
}
});
}
}
}).start();
} else {
Toast.makeText(this, "Network Off", Toast.LENGTH_SHORT).show();
}
AndroidManifest.xml (এই অংশ শুধু <application>
এর মধ্যে বসাবে)
<activity android:name=".SecondActivity"/>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
contex.java code
new Handler().postDelayed(() -> {
startActivity(new Intent(MainActivity.this, SecondActivity.class));
finish();
}, 3000); // 3 সেকেন্ড