I am trying to get WiFi connection changing event using Broadcast Receiver class. I have tested this on Samsung S7 edge and HTC 626Q and it works well (even when the app is closed), but this is not working on Huawei GR5 2017 if the app is closed. It works only when the app is running on screen. Both S7 and GR5 devices have Android 7 (Nougat) OS.
Broadcast Receiver
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,intent.getAction(),Toast.LENGTH_SHORT).show();
}
}
AndroidManifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="chanakamadurangakarunarathne.testbroadcastevents">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_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=".NetworkChangeReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.STATE_CHANGE" />
<action android:name="android.net.nsd.STATE_CHANGED" />
<action android:name="android.net.wifi.NETWORK_IDS_CHANGED" />
<action android:name="android.net.wifi.STATE_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.p2p.CONNECTION_STATE_CHANGE" />
<action android:name="android.net.wifi.p2p.DISCOVERY_STATE_CHANGE" />
<action android:name="android.net.wifi.p2p.PEERS_CHANGED" />
<action android:name="android.net.wifi.p2p.STATE_CHANGED" />
<action android:name="android.net.wifi.p2p.THIS_DEVICE_CHANGED" />
<action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
<action android:name="android.net.wifi.supplicant.STATE_CHANGE" />
</intent-filter>
</receiver>
</application>
</manifest>
I know I can use Services, but It would be nice if I can use Broadcast Receiver for all devices. I found a lot of questions about "Broadcast Receiver not working background" but I couldn't find an answer for my question. Why this happens and is there a way to overcome this (Using Broadcast Receiver only)?