I have a problem updating my AppWidget from within a Service. The problem seems totally illogical to me, so I make a TestService to hunt the mistake down. Here is my testlayout I use:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView android:id="@+id/testText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World"/>
</LinearLayout>
onStart(Intent, startid)
is implemented as following:
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Log.d(TAG, "onStart Service with StartId: " + startId);
mStartId = startId;
int widgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
if (intent != null && intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID)){
widgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
if (widgetId == AppWidgetManager.INVALID_APPWIDGET_ID){
Log.d(TAG, "invalif AppWidgetId");
stopSelf();
}
RemoteViews mRemoteViews = new RemoteViews(getPackageName(), R.layout.testlayout);
mRemoteViews.setTextViewText(R.id.testText, "someText");
AppWidgetManager.getInstance(this).updateAppWidget(widgetId, mRemoteViews);
SystemClock.sleep(1000);
mRemoteViews.setTextViewText(R.id.testText, "text after delay");
AppWidgetManager.getInstance(this).updateAppWidget(widgetId, mRemoteViews);
}
In This implementation, the resulting Widget has always the Text: "someText", but it should be "text after delay" in my point of View. If I remove that Line SystemClock.sleep(1000)
I get the "text after Delay". Why is this?
(Tested on A Samsung Galaxy Nexus (4.1.1)
I have found, that it can be cosidered as a bug that occured on my phone (GalaxyNexus). A restart of the phone fixed it somehow. Like in the 'good old' Windows days, "have you tried to switch it on and off"