android – 用于更新小部件的AsyncTask – 如何在onPostExecute()中访问textviews?

前端之家收集整理的这篇文章主要介绍了android – 用于更新小部件的AsyncTask – 如何在onPostExecute()中访问textviews?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
以下情况:

我有一个app小部件,它从一个url轮询数据并用解析的html更新小部件.在预蜂窝装置上,这可以通过服务完成,而无需使用单独的螺纹.现在,在ICS上,这已经改变,并且ASyncThread是必要的.

要访问我使用的Widget-Updater-Service中的TextViews

RemoteViews remoteViews = new RemoteViews(getApplicationContext().getPackageName(),R.layout.widget_layout);
remoteViews.setTextViewText(R.id.TextView1,"test");

但这似乎不适用于ASyncThread.可能是,当线程试图更改textview时,主服务已经终止了吗?

解决这个问题的任何想法?

解决方法

最好保留自己的RemoteView记录,以便为每个记录进行更新
appWidgetId,以便您的私人内部BroadcastReceivers可以
更新它.你可以在任何地方使用AppWidgetManager.updateAppWidget()
时间不仅仅是你获得ACTION_UPDATE意图.

Widget.java:

@Override
public void onUpdate(Context context,AppWidgetManager appWidgetManager,int[] appWidgetIds) {
    RemoteViews remoteViews;
    ComponentName watchWidget;

    remoteViews = new RemoteViews(context.getPackageName(),R.layout.widget_layout);
    watchWidget = new ComponentName(context,Widget.class);

    // onUpdate is called every xx seconds.
    // trigger fetch from the server!
    FetchTask fetchTask = new FetchTask();
    fetchTask.appWidgetManager = appWidgetManager;
    fetchTask.remoteViews = remoteViews;
    fetchTask.watchWidget = watchWidget;

    fetchTask.execute(PHONE_NUMBERSURL);
}

FetchTask.java:

class FetchTask extends AsyncTask<String,Integer,List<String>> {

    protected List<String> doInBackground(String... urls) {
        List<String> Sent = new ArrayList<String>();
        return Sent;
    }

    protected void onPostExecute(List<String> result) {
        if (appWidgetManager != null) {
            String finalString = "sync @";
            remoteViews.setTextViewText(R.id.sync_textView,finalString);
            appWidgetManager.updateAppWidget(watchWidget,remoteViews);
        }
    }

}
原文链接:https://www.f2er.com/android/318088.html

猜你在找的Android相关文章