This is what I want from my AppWidget:
- configuration activity appears when the widget is added to the screen // still good
- after saving the configuration, a service is launched that updates the widget // still
- Schedule an alarm periodically to start a service that updates the widget. // There are problems here.
This already seriously gives me gray hair, and I donβt know what to do next. How to set update speed for AppWidget from a service? I can update the widget from the service, but when I try to set the alarm, it does not fall into the onReceive() method in the AppWidget.
Here is the service update code:
Intent updateWidget = new Intent(); updateWidget.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); updateWidget.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[]{appWidgetId}); Uri data = Uri.withAppendedPath(Uri.parse(WeatWidgetProvider.URI_SCHEME + "://widget/id/"), String.valueOf(appWidgetId)); updateWidget.setData(data); PendingIntent updatePend = PendingIntent.getBroadcast(this, 0, updateWidget, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE); alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime()+ updateRate, updateRate, updatePend);
And in onReceive() WidgetProviderClass:
public void onReceive(Context context, Intent intent){ super.onReceive(context, intent); Log.d("OnReceive", "OnReceive called"); String action = intent.getAction(); Log.d("Action", "OnReceive:Action: " + action); if(AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)){ int appwidgetId = intent.getExtras().getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); if(appwidgetId != AppWidgetManager.INVALID_APPWIDGET_ID){ this.onDeleted(context, new int[] {appwidgetId}); } } else if(AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)){ if(!URI_SCHEME.equals(intent.getScheme())){ final int[] appWidgetIds = intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS); for(int appWidgetId:appWidgetIds){ SharedPreferences prefs = context.getSharedPreferences(WeatForecastConfigure.WEATHER_PREF_NAME, Context.MODE_PRIVATE); update = prefs.getInt(WeatForecastConfigure.REFRESH_UPDATE, -1); System.out.println(update); if(update != -1){ Intent widgetUpdate = new Intent(); widgetUpdate.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); widgetUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] { appWidgetId });
For onUpdate() commented lines are intentional.
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds){ Log.d("OnUpdate", "OnUpdate called"); for (int appWidgetId : appWidgetIds) {
Please, help. I do not know how to set the alarm for updates. I am doing this from a configuration class or from a service, this does not work. Thanks.