1

如何在处理程序中设置 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...中,但在HandlerRemoteViews 中不存在。我已经尝试了我所知道的一切,到目前为止,什么都没有

4

1 回答 1

1

创建一个新的 :) RemoteViews 刚刚附加到远程实体,并且您几乎将它在实现时所做的一堆更改排队。

所以当你这样做时

appWidgetManager.updateAppWidget(appWidgetId, views);

那是 RemoteViews 真正做某事的时候。

我认为真正的问题是使用的设计有点混乱。所以你有一个线程,不确定它从哪里开始,但它调用了一个处理程序,这很好,但你可能应该发送一些结构化数据,以便处理程序知道该做什么。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. 
              */
          }
        }
}
于 2013-02-23T17:16:30.293 回答