如何在处理程序中设置TextView?
public class DigitalClock extends AppWidgetProvider {
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
int N = appWidgetIds.length;
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.digitalclock);
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
Intent clockIntent = new Intent(context, DeskClock.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
clockIntent, 0);
views.setOnClickPendingIntent(R.id.rl, pendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
private static Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// update your textview here.
}
};
class TickThread extends Thread {
private boolean mRun;
@Override
public void run() {
mRun = true;
while (mRun) {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
mHandler.sendEmptyMessage(0);
}
}
}
我应该在这里更新TextView:
private static Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// update your textview here.
...
我该怎么做?在OnUpdate
方法中,我会使用views.setTextViewText(R.id...
但在Handler
RemoteViews中不存在。我已经尝试了所有我知道的东西,到目前为止,没有什么
答案 0 :(得分:1)
创建一个新的:)远程实体只是连接到远程实体,你几乎排队了它实现时所做的一系列更改。
所以当你这样做时
appWidgetManager.updateAppWidget(appWidgetId, views);
这就是RemoteView实际上做的事情。
我认为真正的问题是所使用的设计有点混乱。所以你有一个线程,不知道它从何处开始但它调用了一个处理程序,这很好,但你应该发送一些结构化数据,以便Handler知道该怎么做。 RemoteViews实例本身是Parcelable,这意味着它们可以作为Intent和Message实例等有效负载的一部分发送。这种设计的真正问题是,如果没有AppWidgetManager实例,您无法调用updateAppWidget来实际执行更改。
您可以在窗口小部件的生命周期内缓存AppWidgetManager,也可以更新更新频率并移动到更多延迟的队列工作者。您从系统收到的下次更新事件的位置,或两者的混合。
private SparseArray<RemoteView> mViews;
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
....
for (int appWidgetId : appWidgetIds) {
RemoteViews v = mViews.get(appWidgetId);
if (v != null) {
appWidgetManager.updateWidget(appWidgetId, v);
} else {
enqueue(appWidgetManager, appWidgetId, new RemoteViews(new RemoteViews(context.getPackageName(),
R.layout.digitalclock)));
/* Enqueue would pretty much associate these pieces of info together
and update their contents on your terms. What you want to do is up
to you. Everytime this update is called though, it will attempt to update
the widget with the info you cached inside the remote view.
*/
}
}
}