I have a BroadcastReciever
name NetworkReciver.java
that executes when Internet is Connected or Disconnected. And it is working well.
But when
Root cause:
From Android N OnePlus introduced a feature similar to Mi devices which prevent certain apps from auto-starting after reboot. I suspect that same feature is preventing your app to receive BroadcastReceiver
as well.
Solution
Use AccessibilityService
service in your app and ask user to turn on AccessibilityService
for your app from Settings and boing doing this BroadcastReceiver
in your app will work as expected.
Since AccessibilityService
is a system level service, so by registering your own service you are passing the certain filter applied by these manufacturers and as soon as your custom AccessibilityService
gets triggered by the OS
, your app becomes active in receiving the eligible BroadcastReceiver
that you had registered.
Here is how you can register your own AccessibilityService
.
Create your custom AccessibilityService
public class MyAccessibilityService extends AccessibilityService {
@Override
public void onAccessibilityEvent(AccessibilityEvent event) {//do nothing }
@Override
public void onInterrupt() { //do nothing}
}
Create configuration file my_accessibility_service.xml
and add below code:
Add permission to AndroidManifest.xml
file:
Add your AccessibilityService
in AndroidManifest.xml
file:
You done!
Below is method to check status of AccessibilityService
:
private static final int ACCESSIBILITY_ENABLED = 1;
public static boolean isAccessibilitySettingsOn(Context context) {
int accessibilityEnabled = 0;
final String service = context.getPackageName() + "/" + MyAccessibilityService.class.getCanonicalName();
try {
accessibilityEnabled = Settings.Secure.getInt(
context.getApplicationContext().getContentResolver(),
android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
} catch (Settings.SettingNotFoundException e) {
Log.e("AU", "Error finding setting, default accessibility to not found: "
+ e.getMessage());
}
TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
if (accessibilityEnabled == ACCESSIBILITY_ENABLED) {
String settingValue = Settings.Secure.getString(
context.getApplicationContext().getContentResolver(),
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
if (settingValue != null) {
mStringColonSplitter.setString(settingValue);
while (mStringColonSplitter.hasNext()) {
String accessibilityService = mStringColonSplitter.next();
if (accessibilityService.equalsIgnoreCase(service)) {
return true;
}
}
}
}
return false;
}
Note: I have not tried but it may help.