I've tried to register a Wifi BroadcastReceiver to get the wifi state when it changes. But so far I have no luck receiving the broadcast.
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<receiver android:name=".WifiReceiver" >
<intent-filter>
<action android:name="android.net.wifi.WifiManager.WIFI_STATE_CHANGED_ACTION" />
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
//activity declaration here...
</application>
Do you guys know how to register the BraodcastReceiver in manifest?
I don't want to register it in activities because I want to monitor the wifi when there is changes in the wifi state whether my application is running or not.
This is my BroadcastReceiver class:
public class WifiReceiver extends BroadcastReceiver {
private final String TAG = "WifiReceiver";
@Override
public void onReceive(Context context, Intent intent) {
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
String wifiStateText = "No State";
switch (wifiState) {
case WifiManager.WIFI_STATE_DISABLING:
wifiStateText = "WIFI_STATE_DISABLING";
break;
case WifiManager.WIFI_STATE_DISABLED:
wifiStateText = "WIFI_STATE_DISABLED";
break;
case WifiManager.WIFI_STATE_ENABLING:
wifiStateText = "WIFI_STATE_ENABLING";
break;
case WifiManager.WIFI_STATE_ENABLED:
wifiStateText = "WIFI_STATE_ENABLED";
break;
case WifiManager.WIFI_STATE_UNKNOWN:
wifiStateText = "WIFI_STATE_UNKNOWN";
break;
default:
break;
}
MyLog.d(TAG, "onReceive Broadcast > WiFiState: " + wifiStateText);
MyLog.d(TAG, "onReceive Broadcast > Time: " + new Date());
}
}
I really hope to get some help. Thanks in advance.
Your receiver in manifest should looks like this
<receiver android:name=".WifiReceiver" >
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
Also the following permission may be needed
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
If your Target android version is more than Android O. if you declare receivers in manifest they wont work. So you need to register inside your activity.
Note: If your app targets API level 26 or higher, you cannot use the manifest to declare a receiver for implicit broadcasts (broadcasts that do not target your app specifically), except for a few implicit broadcasts that are exempted from that restriction. In most cases, you can use scheduled jobs instead.
Resource: https://developer.android.com/guide/components/broadcasts
<receiver android:name=".WifiReceiver" >
<intent-filter android:priority="100" >
<action
android:name="android.net.wifi.WIFI_STATE_CHANGED"
android:enabled="true" />
</intent-filter>
</receiver>
Enter the high priority and also enabled flag as true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With