[android] Change widget in onReceive with custom action

어떤 곳에서 broadcast를 보내고, 그 신호를 받아서 위젯을 바꾼다.

Intent intent = new Intent(getString(R.string.action_notification_event));
intent.putExtra("type", "calendar");
intent.putExtra("name", "asdfasdfasdf");
sendBroadcast(intent);

 

 

처음엔 onUpdate를 호출하는 걸 찾았는데, 나오지가 않았다.

그러다가 겨우 이 소스를 찾아냈다.

위젯…어렵구나

public class MySimpleWidget extends AppWidgetProvider
{
  @Override
  public void onReceive(Context $context, Intent $intent)
  {
    super.onReceive($context, $intent);
    String action = $intent.getAction();
    
    if (action.equals($context.getString(R.string.action_notification_event)))
      updateAppWidgetForCalendar($context, $intent.getStringExtra("name"));
  }


  private void updateAppWidgetForCalendar(Context $context, String $name)
  {
    RemoteViews view = new RemoteViews($context.getPackageName(), R.layout.simple_widget_layout);
    view.setTextViewText(R.id.text_status, $name);
    view.setViewVisibility(R.id.text_status, View.VISIBLE);
    
    Intent intent = new Intent();
    ComponentName cn = new ComponentName("com.google.android.calendar", "com.android.calendar.LaunchActivity");
    intent.setComponent(cn);
    
    PendingIntent pendingIntent = PendingIntent.getActivity($context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    view.setOnClickPendingIntent(R.id.text_status, pendingIntent);
    
    ComponentName thisWidget = new ComponentName($context, MySimpleWidget.class);
    AppWidgetManager manager = AppWidgetManager.getInstance($context);
    manager.updateAppWidget(thisWidget, view);
  }
}