1

I'm trying yo make a simple widget with clickable image that will change when its clicked. I don't understand why it doesn't work

   public class AppWidget extends AppWidgetProvider {

@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction()==null) {
    context.startService(new Intent(context,
            ToggleService.class));

} else {
super.onReceive(context, intent);
}

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

}
public static class ToggleService extends IntentService { 
    public ToggleService() { 
        super("AppWidget$ToggleService");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
    ComponentName me=new ComponentName(this, AppWidget.class);
    AppWidgetManager mgr=AppWidgetManager.getInstance(this);
    mgr.updateAppWidget(me, buildUpdate(this));
    }
    private RemoteViews buildUpdate(Context context) {
    RemoteViews updateViews=new
    RemoteViews(context.getPackageName(),R.layout.widget);
    int a = 1;
    if(a ==
            1) {

            updateViews.setImageViewResource(R.id.phoneState,
            R.drawable.dual_off);
    } else {
    updateViews.setImageViewResource(R.id.phoneState,
    R.drawable.dual_on);
    }
    Intent i=new Intent(this, AppWidget.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, i,0); 
    updateViews.setOnClickPendingIntent(R.id.phoneState,pi); 
    return updateViews; 
    }
}




 }

I have tried all sort of things in for loop but it just won't change image. I have done this from a book about android development, am new to java and android.

Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
pedja
  • 3,285
  • 5
  • 36
  • 48

1 Answers1

0

You would to update your widget by AppWidgetManager, after changing remoteview's source.In this snippet code I try to change layout of widget that it's AppWidgetProvider name is DictionWidgetProvider :

private void hideWidgetInstances() {
    hideViews = new RemoteViews(App.getContext().getPackageName(),
    R.layout.hide);
    AppWidgetManager mManager = AppWidgetManager.getInstance(App
    .getContext());
    ComponentName cn = new ComponentName(App.getContext(),
    DictionWidgetProvider.class);
    mManager.updateAppWidget(cn, hideViews);
}

Here App is a class that extends Application.You can use Application Context to reach ComponentName.

hasanghaforian
  • 13,858
  • 11
  • 76
  • 167