1

Chosen answer in duplicate is WRONG.

It will produce NPE if the widget app restarts.

——————————

It is a TorchWidget app, contains 2 classes:

class1 AppWidgetProvider

  • setOnClickPendingIntent to start class2

  • new RemoteViews to set initial button icon.

class2 IntentService

  • switch torch

  • new another RemoteViews to switch on/off icon.

    RemoteViews views = new RemoteViews(getPackageName(), R.layout.torch);
    
    if (b) {
        mSwitch(Service.this, false);
        views.setImageViewResource(R.id.Torch,R.drawable.moon_off );
        editor.putBoolean("switch", false);
    } else {
        mSwitch(Service.this, true);
        views.setImageViewResource(R.id.Torch,R.drawable.moon_on );
        editor.putBoolean("switch", true);
    }
    

Full Code on Github.

userA789
  • 425
  • 2
  • 6
  • 17

1 Answers1

0

After restart, the restored view will be the one instantiated in IntentService, which is without OnClickPendingIntent.

To solve the problem, I should change icon only in update function in provider via broadcasts.

still a question, why the OnClickPendingIntent will work until launcher restart, after view is replaced.

userA789
  • 425
  • 2
  • 6
  • 17