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 class2new
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.