Trying to call the broadcast receiver called NetworkReceiver on network change. The same code in java works but doesn't work when trying to do it in Kotlin. The receiver is never called when the connection happens or when it is lost. Im trying to do it in emulator. Also the receiver isn't called when the boot is completed. Also Im testing this on Android Oreo i.e. Android 8.0
NetworkReceiver.kt
class NetworkReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
Logs.v("onReceive")
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = connectivityManager.activeNetworkInfo
if (networkInfo != null && networkInfo.detailedState == NetworkInfo.DetailedState.CONNECTED) {
Logs.v("Network Connected")
} else if (networkInfo != null) {
val state = networkInfo.detailedState
Logs.v("NetworkReceiver", state.name)
} else {
Logs.v("Network Connected")
}
}
}
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.android.client">
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name=".application.App"
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">
<receiver android:name=".network.NetworkReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
<activity
android:name=".views.activities.kt.LoginActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".views.activities.kt.DashboardActivity"
android:label="@string/title_activity_dashboard"
android:theme="@style/AppTheme.NoActionBar" />
<activity android:name=".views.activities.kt.ConfigurationActivity"
android:label="@string/title_activity_configuration"
android:theme="@style/AppTheme.NoActionBar"/>
</application>
</manifest>