2013-02-23 78 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. 
       */ 
      } 
     } 
}