小部件不在创建时更新? - Android

时间:2015-11-08 04:26:19

标签: android widget android-widget

我有一个小工具,可以在点击按钮时显示天气。小部件应该在第一次创建时执行此更新,但事实并非如此。我把它放在主屏幕上后,我必须手动点击更新它。

问。如何在创建小部件后自动更新小部件?

我尝试过的事情:

  1. 在Widget提供程序中使用onEnabled
  2. 在Widget提供程序中使用onRecieve
  3. 我的WidgetProvider:

    public class Widget extends AppWidgetProvider {
        @Override
        public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                             int[] appWidgetIds) {
    
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);
            views.setOnClickPendingIntent(R.id.rButton, buildButtonPendingIntent(context));
    
            pushWidgetUpdate(context, views);
        }
        public static PendingIntent buildButtonPendingIntent(Context context) {
            Intent intent = new Intent();
            intent.setAction("update");
            return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    
        public static void pushWidgetUpdate(Context context, RemoteViews views) {
            ComponentName myWidget = new ComponentName(context, Widget.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(context);
            manager.updateAppWidget(myWidget, views);
        }
    }
    

    我的BroadcastReceiver:

    public class WidgetReceiver extends BroadcastReceiver {
        double lat, lon;
        String xtemp, xmaxtemp, xmintemp, xcity, xweather, provider, weatherpic;
        Location loc;
        LocationManager mlocManager;
        //======================================= OnReceive Method
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (intent.getAction().equals("update")) {
                    new MyAsyncTask2().execute(context);
                }
            } catch (Exception e){
                e.printStackTrace();
            }
        }
        public class MyAsyncTask2 extends AsyncTask<Context, Void, String> {
        //Does all the update for the weather and shows it on the textViews                  
        } 
    }
    

    我是Widget编程的新手,让我知道我是否可以进行任何优化! :)

0 个答案:

没有答案