Android App Widget - 更新中的 AsyncTask API 调用

Posted

技术标签:

【中文标题】Android App Widget - 更新中的 AsyncTask API 调用【英文标题】:Android App Widget - AsyncTask API call in update 【发布时间】:2016-10-05 02:27:47 【问题描述】:

我想在我的 android 主屏幕上制作一个简单的小部件,我可以在其中填写我的邮政编码或城市,并通过提交该数据,我希望能够使用来自对 Openweathermap 的 API 调用的数据更新小部件.org。

我已采取一切措施使其正常工作,但由于某种原因,Widget textView 不会随着收集的数据而更新。

这是我的主要活动。

public class WeerManWidget extends AppWidgetProvider 

public static String ACTION_WIDGET_CONFIGURE = "ConfigureWidget";

static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) 

    CharSequence widgetText = WeerManWidgetConfigureActivity.loadTitlePref(context, appWidgetId);
    // Construct the RemoteViews object
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.weer_man_widget);
    views.setTextViewText(R.id.appwidget_text, widgetText);



    Intent configIntent = new Intent(context, WeerManWidgetConfigureActivity.class);
    configIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
    PendingIntent configPendingIntent = PendingIntent.getActivity(context, appWidgetId, configIntent, 0);
    views.setOnClickPendingIntent(R.id.btnSettings, configPendingIntent);
    configIntent.setAction(ACTION_WIDGET_CONFIGURE + Integer.toString(appWidgetId));



    new GetWeatherTask(views).execute(widgetText.toString());



    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views);


@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) 
    // There may be multiple widgets active, so update all of them
    for (int appWidgetId : appWidgetIds) 
        updateAppWidget(context, appWidgetManager, appWidgetId);
    


@Override
public void onDeleted(Context context, int[] appWidgetIds) 
    // When the user deletes the widget, delete the preference associated with it.
    for (int appWidgetId : appWidgetIds) 
        WeerManWidgetConfigureActivity.deleteTitlePref(context, appWidgetId);
    


@Override
public void onEnabled(Context context) 
    // Enter relevant functionality for when the first widget is created


@Override
public void onDisabled(Context context) 
    // Enter relevant functionality for when the last widget is disabled


这是我用于 API 调用的类。

public class GetWeatherTask extends AsyncTask<String, String, String> 

private RemoteViews views;

GetWeatherTask(RemoteViews views) 
    this.views = views;


@Override
public String doInBackground(String... params) 

    String postalCode = params[0];

    HttpURLConnection urlConnection = null;
    URL url = null;
    JSONObject object = null;
    JSONArray myArray = null;
    InputStream inStream = null;

    try 
        url = new URL("http://api.openweathermap.org/data/2.5/weather?q="+postalCode+",nl&appid=XXXXX&units=metric");
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.connect();

        inStream = urlConnection.getInputStream();
        BufferedReader bReader = new BufferedReader(new InputStreamReader(inStream));
        String temp, response = "";
        while ((temp = bReader.readLine()) != null) 
            response += temp;
        

        object = (JSONObject) new JSONTokener(response).nextValue();
        JSONObject obj = object.getJSONObject("main");
        String weatherTemp = obj.getString("temp");

        double weatherFloat = Double.parseDouble(weatherTemp);
        //weatherFloat = (weatherFloat - 273.15);

        String newTemp = String.valueOf(weatherFloat);

        return newTemp;
     catch (Exception e) 

        return e.toString();
     finally 
        if (inStream != null) 
            try 
                inStream.close();
             catch (IOException ignored) 

            
        
        if (urlConnection != null) 
            urlConnection.disconnect();
        
    


@Override
public void onPostExecute(String result) 
    Log.v("WeerManWidget", result);

    views.setTextViewText(R.id.appwidget_text, result);


在 AsyncTask 中的 onPostExecute 中看到,我记录了结果。这有正确的数据。所以一切都很好,但是当我想用 setTextViewText 更新视图时,什么也没有发生。我是 Android 开发新手,没有想法。

有大神指教一下吗?

【问题讨论】:

【参考方案1】:

调用 API 并使用后:

views.setTextViewText(R.id.appwidget_text, result);

您需要使用AppWidgetManager 来更新 UI。

这是一个例子:

AppWidgetManager manager=AppWidgetManager.getInstance(context);
manager.updateAppWidget(widgetID,views);

【讨论】:

以上是关于Android App Widget - 更新中的 AsyncTask API 调用的主要内容,如果未能解决你的问题,请参考以下文章

Android:我的带有 ListView 的 App Widget 未通过按钮或更新周期进行更新

android.support.v4.app.FragmentTabHost 无法转换为 android.widget.LinearLayout

Android- Widget (应用微件/小组件/插件) 使用介绍

Android 之窗口小部件详解--App Widget

android appwidget 中的更新这个概念怎么理解? 为什需要更新?

在 Android 12 中使用 widget