2013-02-23 29 views
1

如何在处理程序中设置TextView?在Handler和Thread Widget中设置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不存在。我试过了我所知道的一切,到目前为止,没有任何东西

回答

1

创建一个新的:)远程视图只是附加到远程实体,你几乎排队了它实现时所做的一系列更改。

所以,当你做

appWidgetManager.updateAppWidget(appWidgetId, views); 

也就是说当RemoteViews真正做一些事情。

我认为真正的问题是所用的设计有点杂乱。所以你有一个线程,不确定它在哪里开始,但它调用了一个处理程序,这很好,但你应该发送一些结构化数据,以便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. 
       */ 
      } 
     } 
}