Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to rely on the call to onDataSetChanged() after onCreated() in RemoteViewsFactory of an AppWidget

I developed my AppWidget according to the android doc, loading my cursor in onCreate() and reloading it in onDataSetChanged(), and everything worked fine, until I set some breakpoints in my RemoteViewsService.RemoteViewsFactory and surprisingly found that onDataSetChanged() is always called after the call to onCreate(), which made my cursor loaded twice when first created. I'm on Android 4.4.3.

According to the Api doc,

public abstract void onDataSetChanged ()

Added in API level 11

Called when notifyDataSetChanged() is triggered on the remote adapter. This allows a RemoteViewsFactory to respond to data changes by updating any internal references. Note: expensive tasks can be safely performed synchronously within this method. In the interim, the old data will be displayed within the widget.

Seems that this call is only triggered by manually calling notifyDataSetChanged() ourselves.

However acccording to the Appwidget guide,

In onCreate() you setup any connections / cursors to your data source. Heavy lifting, for example downloading or creating content etc, should be deferred to onDataSetChanged() or getViewAt(). Taking more than 20 seconds in this call will result in an ANR.

By saying deferred, is it implying that onDataSetChanged() will be called after onCreate()? I'm not so sure... However it does say I should setup my cursor inside onCreate().

I tried to investigate this issue myself, however the available source code is using Binder so the remote caller remains unknown, thus I cannot inspect its source.

Do you have any idea?

like image 785
Hai Zhang Avatar asked Aug 12 '14 08:08

Hai Zhang


1 Answers

As you can see in your linked guide, onDataSetChanged is every time called after onCreate:

Data flow

(App Widgets | Android Developers)

So it's safe to load your cursor in onDataSetChanged

like image 174
Auroratic Avatar answered Oct 23 '22 11:10

Auroratic