thesquare12
thesquare12

Reputation: 23

App widget is not updated in power saving mode

I have a widget that has network access.
Updating widgets in power saving mode results in a timeout exception.
It turns out that handling the battery optimization exception will resolve it.
But some apps have seen network access in widgets without any battery optimization exceptions.

How are they possible?

Here is my subclass of AppWidgetProvider.

public class WidgetProvider4x2 extends AppWidgetProvider {

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        for (int appWidgetId : appWidgetIds) {
            requestApi();
        }
    }

    private void requrestApi() {
        // timeout occurs
    }
}

Upvotes: 0

Views: 1026

Answers (2)

rubenwardy
rubenwardy

Reputation: 683

Loading data on user action

Slightly different use case here - we wanted to load data on a user action, when the user taps a refresh button.

I looked into using wifi wakelocks, foreground services, and the workmanager but none of these worked immediately on user action. In the end, the solution I found was to use an activity.

When power saving mode is off, the data is loaded as normal. If power saving mode is on, we show a message and a button on the widget that opens up a WidgetRefreshActivity that stays open whilst the app is getting data. When finished, the activity closes.

Background updates

Take a look at WorkManager with NetworkType.CONNECTED. I haven't been able to verify this, but I believe this allows you to update your widget when Android has turned on networking to update all apps. https://developer.android.com/guide/background/persistent/migrate-from-legacy/gcm#schedule-work

Upvotes: 0

ilham suaib
ilham suaib

Reputation: 422

That's because when power saving mode on makes RESTRICT_BACKGROUND_STATUS_ENABLED is true. When RESTRICT_BACKGROUND_STATUS_ENABLED is true we can't load/fetch data from network outside view layer eg. activity/fragment. To solve this you can request data restriction permission using intent.

Intent intent = new Intent(Settings.ACTION_IGNORE_BACKGROUND_DATA_RESTRICTIONS_SETTINGS, Uri.parse("package:" + getPackageName()));
            startActivity(intent);

Upvotes: 2

Related Questions