Search code examples
javaandroidbroadcastreceiverandroid-widget

BroadcastReceiver with acton SCREEN_ON in background


I want to listen when screen of device is on and update widget but BroadcastReceiver does not work when I close my app. It works only when application is running.

AndroidManifest.xml:

    <receiver
        android:name=".WidgetProvider"
        android:exported="true">
        <intent-filter>
            <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            <action android:name="android.intent.action.SCREEN_ON"/>
            <action android:name="android.intent.action.SCREEN_OFF"/>
        </intent-filter>
        <meta-data
            android:name="android.appwidget.provider"
            android:resource="@xml/widget_info"/>
    </receiver>

The code is in onCreate():

    IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_ON);
    intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
    BroadcastReceiver mReceiver = new WidgetProvider();
    registerReceiver(mReceiver, intentFilter);

Solution

  • Since Android 8, the background processes have been restricted due to safety and battery consumption. Some Broadcast Receivers like:-

    1. SCREEN_OFF
    2. TIME_TICK
    3. etc..

    have been blocked.But, some of them like this:

    1. REBOOT

    work fine. This is to save the battery consumptions. This also prevents our app from opening activities when they are not necessary too.