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);
Since Android 8, the background processes have been restricted due to safety and battery consumption. Some Broadcast Receivers like:-
have been blocked.But, some of them like this:
work fine. This is to save the battery consumptions. This also prevents our app from opening activities when they are not necessary too.