我从服务中更新 AppWidget 时遇到问题。这个问题对我来说似乎完全不合逻辑,所以我创建了一个 TestService 来查找错误。这是我使用的测试布局:
<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)
实现如下:
@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);
}
在此实现中,生成的小部件始终具有文本:“someText”,但在我看来,它应该是“延迟后的文本”。如果我删除该行,SystemClock.sleep(1000)
我会得到“延迟后的文本”。为什么是这样?(在三星 Galaxy Nexus (4.1.1) 上测试