Android appwidget not starting

When I work in debug mode, I cannot find any breakpoints that are inside the service, why?

    @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
    context.startService(new Intent(context, UpdateService.class));
}

public static class UpdateService extends Service {

    @Override
    public void onStart(Intent intent, int startId) {
        // Build the widget update for today
        RemoteViews updateViews = buildUpdate(this);

        // Push update for this widget to the home screen
        ComponentName thisWidget = new ComponentName(this, WidgetProvider.class);
        AppWidgetManager manager = AppWidgetManager.getInstance(this);
        manager.updateAppWidget(thisWidget, updateViews);
    }

    public RemoteViews buildUpdate(Context context) {
        return new RemoteViews(context.getPackageName(), R.id.widget_main_layout);
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
+3
source share
3 answers

The onUpdate method is executed only if the widget is initialized (for example, placed on the desktop) or updatePeriodMillis expires. If you want to perform a service, for example. by clicking on the widget, you should “attach” the pending intent as follows:

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final Intent intent = new Intent(context, UpdateService.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);

// Get the layout for the App Widget and attach an on-click listener to
// the button
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout....);
views.setOnClickPendingIntent(R.id.button, pendingIntent);
for(int i=0,n=appWidgetIds.length;i<n;i++){
    int appWidgetId = appWidgetIds[i];
    appWidgetManager.updateAppWidget(appWidgetId , views);
}

(cleaned version of the working widget).

The fact is that the onUpdate () method is really very rarely executed. Actual interaction with widgets is set using pending intentions.

+2
source

Service . AppWidgetProvider .

+2

, , , . updateViews() , android: updatePeriodMillis 86400000 XML, . XML :

<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
  android:minWidth="72dp"
  android:maxWidth="72dp"
  android:updatePeriodMillis="86400000" >
</appwidget-provider>

, appwidget , , , . , , 30 , : updatePeriodMillis ( - 30 ) AlarmManager, , , .

0
source

Source: https://habr.com/ru/post/1794454/


All Articles