I am trying to create an application that tracks internet connection. When internet connectivity status changes, it should make a toast. For this, I am supposed to use Broadcast Receiver. So far, I've written (found) this code (following code only includes parts related to this job)
ConnectivityReceiver mConnectivityReceiver;
IntentFilter mConnectivityIntentFilter;
@Override
protected void onCreate(Bundle savedInstanceState) {
....
mConnectivityIntentFilter = new IntentFilter();
mConnectivityIntentFilter.addAction(Intent.ACTION_MANAGE_NETWORK_USAGE);
mConnectivityReceiver = new ConnectivityReceiver();
....
}
@Override
protected void onResume() {
super.onResume();
registerReceiver(mConnectivityReceiver, mConnectivityIntentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(mConnectivityReceiver);
}
public class ConnectivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("onreceive", "success");
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
boolean isWifiConn = false;
boolean isMobileConn = false;
for (Network network : connMgr.getAllNetworks()) {
NetworkInfo networkInfo = connMgr.getNetworkInfo(network);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
isWifiConn |= networkInfo.isConnected();
}
if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
isMobileConn |= networkInfo.isConnected();
}
}
if (isMobileConn || isWifiConn) {
Toast.makeText(getApplicationContext(), "Internet connected", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(), "Internet connection lost, may cause some functions to not work properly", Toast.LENGTH_LONG).show();
}
}
}
I have these two permissions in manifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
I tried on both emulator (Android 8.0) and device (Android 5.1), my code doesn't work. It doesn't make a toast and it doesn't even create the log.
What am I doing wrong?
Thanks in advance!