@Override
  public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

    // Definisco il layout del widget e mi salvo la sua istanza in remoteViews
    RemoteViews remoteViews =
        new RemoteViews(context.getPackageName(), R.layout.widget_chronometer);
    remoteViews.setOnClickPendingIntent(R.id.level, startButtonPendingIntent(context));

    IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = context.registerReceiver(null, ifilter);
    int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
    int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

    int batteryPct = level * 100 / scale;
    remoteViews.setTextViewText(R.id.level, batteryPct + "%");

    if (batteryPct < 15) {
      remoteViews.setTextColor(R.id.level, Color.RED);
    } else {
      if (batteryPct < 50) {
        remoteViews.setTextColor(R.id.level, Color.YELLOW);
      } else {
        remoteViews.setTextColor(R.id.level, Color.GREEN);
      }
    }

    pushWidgetUpdate(context, remoteViews);
  }
  private void handleIsOpen(final Context mContext, final OpeningStatus openingStatus) {
    final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
    final int[] appWidgetIds =
        appWidgetManager.getAppWidgetIds(new ComponentName(mContext, AnalogWidget.class));
    final RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.analog_widget);
    views.setTextViewText(R.id.appwidget_text, mContext.getText(R.string.refreshing_analog));
    views.setTextColor(
        R.id.appwidget_text, ContextCompat.getColor(mContext, android.R.color.primary_text_dark));
    // Instruct the widget manager to update the widget
    for (int appWidgetId : appWidgetIds) {
      appWidgetManager.updateAppWidget(appWidgetId, views);
    }

    CharSequence widgetText;
    if (openingStatus.open) {
      widgetText = mContext.getString(R.string.widget_open_analog);
      views.setTextColor(R.id.appwidget_text, ContextCompat.getColor(mContext, R.color.openColor));
    } else {
      widgetText = mContext.getString(R.string.widget_closed_analog);
      views.setTextColor(
          R.id.appwidget_text, ContextCompat.getColor(mContext, R.color.closedColor));
    }

    views.setTextViewText(R.id.appwidget_text, widgetText);
    views.setOnClickPendingIntent(R.id.appwidget_text, getPendingSelfIntent(mContext));
    // Instruct the widget manager to update the widget
    for (int appWidgetId : appWidgetIds) {
      appWidgetManager.updateAppWidget(appWidgetId, views);
    }
  }
  private void setDefaultDayColor(RemoteViews remoteViews, int position) {

    if (position >= 0 && (position + 1) % 7 == 0) {
      remoteViews.setTextColor(R.id.text_day, Color.BLUE);
    } else if (position >= 0 && (position + 1) % 7 == 1) {
      remoteViews.setTextColor(R.id.text_day, Color.RED);
    } else {
      remoteViews.setTextColor(R.id.text_day, Color.WHITE);
    }
  }
  private static void updateWidget(
      Context context,
      AppWidgetManager appWidgetManager,
      WidgetModel widgetModel,
      ArrayList<ArrivalModel> arrivals) {
    // Set the base layout to use
    int layoutResId =
        widgetModel.getSize() == WidgetUtils.SIZE_1X1
            ? R.layout.widget_layout_1x1
            : R.layout.widget_layout_2x1;
    RemoteViews updatedViews = new RemoteViews(context.getPackageName(), layoutResId);

    // Set widget background colors
    updatedViews.setInt(
        R.id.tv_widget_title,
        SET_BACKGROUND_COLOR,
        WidgetUtils.getPrimaryColorInt(context, widgetModel.getBgColor()));
    updatedViews.setInt(
        R.id.layout_widget_arrivals,
        SET_BACKGROUND_COLOR,
        WidgetUtils.getSecondaryColorInt(context, widgetModel.getBgColor()));

    // If the user set the widget color to white, we have to change the colors of
    // some UI elements so that they show properly.
    if (widgetModel.getBgColor() == WidgetUtils.BG_WHITE) {
      updatedViews.setTextColor(R.id.tv_widget_title, Color.DKGRAY);
      updatedViews.setTextColor(R.id.tv_widget_arrival_1, Color.DKGRAY);
      updatedViews.setTextColor(R.id.tv_widget_arrival_2, Color.DKGRAY);
      updatedViews.setInt(R.id.iv_widget_divider_1, SET_BACKGROUND_COLOR, Color.DKGRAY);
      if (getNumArrivalsToShow(widgetModel) == 3) {
        // There is a third arrival text to update
        updatedViews.setTextColor(R.id.tv_widget_arrival_3, Color.DKGRAY);
        updatedViews.setInt(R.id.iv_widget_divider_2, SET_BACKGROUND_COLOR, Color.DKGRAY);
      }
    }

    // Set the widget title
    updatedViews.setTextViewText(R.id.tv_widget_title, widgetModel.getTitle());

    // Update the shown arrival times
    for (int i = 0; i < Math.min(arrivals.size(), getNumArrivalsToShow(widgetModel)); i++) {
      updatedViews.setTextViewText(
          ARRIVAL_TEXTVIEW_RES_ID[i], String.valueOf(arrivals.get(i).getMinsUntilArrival()));
    }

    // Set the widget to refresh on click
    updatedViews.setOnClickPendingIntent(
        R.id.tv_widget_title, createRefreshIntent(context, widgetModel.getWidgetId()));
    updatedViews.setOnClickPendingIntent(
        R.id.layout_widget_arrivals, createRefreshIntent(context, widgetModel.getWidgetId()));

    // Update the widget view
    appWidgetManager.updateAppWidget(widgetModel.getWidgetId(), updatedViews);
  }
  private RemoteViews buildView() {
    SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    int colorHour = sharedPrefs.getInt(ConstantsPrefs.colorHour, R.integer.COLOR_DEFAULT);
    int colorDay = sharedPrefs.getInt(ConstantsPrefs.colorDay, R.integer.COLOR_DEFAULT);

    remoteViews.setTextColor(R.id.hour, colorHour);

    remoteViews.setTextColor(R.id.day, colorDay);

    remoteViews.setTextViewText(R.id.hour, hour);
    remoteViews.setTextViewText(R.id.day, day);

    return remoteViews;
  }
  @Override
  public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    final int N = appWidgetIds.length;
    for (int i = 0; i < N; i++) {
      int appWidgetId = appWidgetIds[i];

      /* set on click for the AppWidget layout */
      Intent layoutIntent = new Intent(context, MainActivity.class);
      layoutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
      PendingIntent layoutPendingIntent = PendingIntent.getActivity(context, 0, layoutIntent, 0);
      RemoteViews widgetView =
          new RemoteViews(context.getPackageName(), R.layout.appwidget_homescreen);
      widgetView.setOnClickPendingIntent(R.id.widget_layout, layoutPendingIntent);

      // Color theme
      SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
      int txtColor = sharedPref.getInt(PreferencesActivity.KEY_PREF_TXT_COLOR, 1);
      Bitmap b = Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888);
      Canvas c = new Canvas(b);
      c.drawColor(txtColor);
      widgetView.setTextColor(R.id.tvAppWidgetArtist, txtColor);
      widgetView.setTextColor(R.id.tvAppWidgetTitle, txtColor);
      widgetView.setImageViewBitmap(R.id.ivAppWidgetHS, b);
      widgetView.setImageViewBitmap(R.id.ivAppWidgetVS, b);

      /* set on click for the AppWidget 'next' button */
      Intent playNextIntent = new Intent(context, SongService.class);
      playNextIntent.putExtra("action", "next");
      PendingIntent playNextPendingIntent = PendingIntent.getService(context, 1, playNextIntent, 0);
      widgetView.setOnClickPendingIntent(R.id.ibAppWidgetNext, playNextPendingIntent);

      /* set on click for the AppWidget 'play/pause' button */
      Intent playOrPauseIntent = new Intent(context, SongService.class);
      playOrPauseIntent.putExtra("action", "playOrPause");
      PendingIntent playOrPausePendingIntent =
          PendingIntent.getService(context, 2, playOrPauseIntent, 0);
      widgetView.setOnClickPendingIntent(R.id.ibAppWidgetPlayPause, playOrPausePendingIntent);

      /* set on click for the AppWidget 'previous' button */
      Intent playPreviousIntent = new Intent(context, SongService.class);
      playPreviousIntent.putExtra("action", "previous");
      PendingIntent playPreviousPendingIntent =
          PendingIntent.getService(context, 3, playPreviousIntent, 0);
      widgetView.setOnClickPendingIntent(R.id.ibAppWidgetPrevious, playPreviousPendingIntent);

      appWidgetManager.updateAppWidget(appWidgetId, widgetView);
    }
  }
 private static RemoteViews errorUpdate(Context context) {
   RemoteViews updateViews =
       new RemoteViews(context.getPackageName(), R.layout.widget_2x1_no_data);
   updateViews.setTextViewText(R.id.line1, "Error!");
   updateViews.setTextColor(R.id.line1, Color.RED);
   return updateViews;
 }
Exemple #8
0
  @Override
  public RemoteViews getViewAt(int position) {
    if (items == null || position < 0 || position >= items.size()) {
      return null;
    } else {
      // todo cache?
      final Resources r = context.getResources();
      final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
      final int todayDueDateColor =
          prefs.getInt(Preferences.DUE_TODAY_COLOR, r.getColor(R.color.today_due_date_color));
      final int expiredDueDateColor =
          prefs.getInt(Preferences.OVERDUE_COLOR, r.getColor(R.color.expired_due_date_color));
      final int completedColor = r.getColor(R.color.widget_completed);
      final int defaultColor = r.getColor(R.color.white);

      TodoItem item = items.get(position);

      RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget_item);
      rv.setTextViewText(R.id.widget_item, item.summary);
      rv.setTextColor(
          R.id.widget_item,
          getItemColor(defaultColor, completedColor, todayDueDateColor, expiredDueDateColor, item));

      final Intent fillInIntent = new Intent();
      final Bundle bundle = new Bundle();
      bundle.putLong(KTodoWidgetProvider.ON_ITEM_CLICK_ITEM_ID_EXTRA, item.id);
      bundle.putLong(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
      fillInIntent.putExtras(bundle);
      rv.setOnClickFillInIntent(R.id.widget_item, fillInIntent);

      return rv;
    }
  }
 /**
  * 设置下载进度和当前的网速
  *
  * @param progress
  * @param netSpeed
  */
 private void setProgressAndNetSpeed(int progress, long netSpeed) {
   remoteViews.setTextViewText(R.id.download_notication_title, bookName + "   " + progress + "%");
   remoteViews.setProgressBar(R.id.progress, 100, progress, false);
   remoteViews.setTextViewText(R.id.tv_progress, netSpeed + "kb/s");
   if (android.os.Build.VERSION.SDK_INT <= 9)
     remoteViews.setTextColor(
         R.id.download_notication_title,
         mContext.getResources().getColor(R.color.alarm_playback_color));
   notifiManger.notify(NOTIFI_ID, notification);
   lastTotalRxBytes = getTotalRxBytes();
   lastTimeStamp = System.currentTimeMillis();
 }
  public RemoteViews buildUpdate(int position) {
    try {
      Task task = getTask(position);

      String textContent;
      Resources r = context.getResources();
      int textColor =
          r.getColor(dark ? R.color.widget_text_color_dark : R.color.widget_text_color_light);

      textContent = task.getTitle();

      RemoteViews row = new RemoteViews(Constants.PACKAGE, R.layout.widget_row);

      if (task.isCompleted()) {
        textColor = r.getColor(R.color.task_list_done);
        row.setInt(R.id.text, "setPaintFlags", Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
      } else {
        row.setInt(R.id.text, "setPaintFlags", Paint.ANTI_ALIAS_FLAG);
        if (task.hasDueDate() && task.isOverdue()) {
          textColor = r.getColor(R.color.task_list_overdue);
        }
      }

      row.setTextViewText(R.id.text, textContent);
      row.setTextColor(R.id.text, textColor);
      row.setImageViewResource(R.id.completeBox, getCheckbox(task));

      Intent editIntent = new Intent();
      editIntent.setAction(TasksWidget.EDIT_TASK);
      editIntent.putExtra(TaskEditFragment.TOKEN_ID, task.getId());
      editIntent.putExtra(TaskListActivity.OPEN_TASK, task.getId());
      row.setOnClickFillInIntent(R.id.text, editIntent);

      Intent completeIntent = new Intent();
      completeIntent.setAction(TasksWidget.COMPLETE_TASK);
      completeIntent.putExtra(TaskEditFragment.TOKEN_ID, task.getId());
      row.setOnClickFillInIntent(R.id.completeBox, completeIntent);

      return row;
    } catch (Exception e) {
      // can happen if database is not ready
      Log.e("WIDGET-UPDATE", "Error updating widget", e);
    }

    return null;
  }
  private void updateWidget(Context context, AppWidgetManager appWidgetManager) {
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget);

    Intent defineIntent = new Intent(Intent.ACTION_MAIN, null, context, MoneyTracker.class);
    PendingIntent pendingIntent =
        PendingIntent.getActivity(context, 0, defineIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
    views.setOnClickPendingIntent(R.id.thewidget, pendingIntent);

    double remaining = new ExpensesDbHelper(context).remaining();

    String formatted = MoneyTracker.formatRemaining(remaining);
    views.setTextViewText(R.id.disposable, formatted);

    views.setTextViewText(R.id.remaining, remaining < 0 ? "over budget" : "remaining");

    views.setTextColor(R.id.disposable, remaining < 0 ? 0xFFFF0000 : 0xFF000000);

    appWidgetManager.updateAppWidget(
        new ComponentName(context, MoneyTrackerWidgetProvider.class), views);
  }
Exemple #12
0
  /** Update the widget appWidgetId */
  private static void updateWidget(Context context, int appWidgetId) {
    Log.v(TAG, "updateWidget appWidgetId: " + appWidgetId);
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
    PendingIntent clickIntent;

    // Launch an intent to avoid ANRs
    final Intent intent = new Intent(context, WidgetService.class);
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
    intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
    remoteViews.setRemoteAdapter(appWidgetId, R.id.conversation_list, intent);

    remoteViews.setTextViewText(
        R.id.widget_label, context.getString(R.string.title_conversation_list));
    remoteViews.setTextColor(R.id.widget_label, ThemeManager.getTextOnColorPrimary());

    remoteViews.setInt(
        R.id.conversation_list_background, "setColorFilter", ThemeManager.getBackgroundColor());
    remoteViews.setInt(R.id.header_background, "setColorFilter", ThemeManager.getColor());

    // Open Mms's app conversation list when click on header
    final Intent convIntent = new Intent(context, MainActivity.class);
    clickIntent =
        PendingIntent.getActivity(context, 0, convIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    remoteViews.setOnClickPendingIntent(R.id.widget_header, clickIntent);

    // On click intent for Compose
    final Intent composeIntent = new Intent(context, QKComposeActivity.class);
    clickIntent =
        PendingIntent.getActivity(context, 0, composeIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    remoteViews.setOnClickPendingIntent(R.id.widget_compose, clickIntent);

    // On click intent for Conversation
    Intent startActivityIntent = new Intent(context, MainActivity.class);
    PendingIntent startActivityPendingIntent =
        PendingIntent.getActivity(
            context, 0, startActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    remoteViews.setPendingIntentTemplate(R.id.conversation_list, startActivityPendingIntent);

    AppWidgetManager.getInstance(context).updateAppWidget(appWidgetId, remoteViews);
  }
 private static RemoteViews updateWidgetFromAccount(
     Context context, int widgetId, int layoutId, Class providerClass, Account a) {
   RemoteViews updateViews = new RemoteViews(context.getPackageName(), layoutId);
   updateViews.setTextViewText(R.id.line1, a.title);
   AccountType type = AccountType.valueOf(a.type);
   if (type.isCard && a.cardIssuer != null) {
     CardIssuer cardIssuer = CardIssuer.valueOf(a.cardIssuer);
     updateViews.setImageViewResource(R.id.account_icon, cardIssuer.iconId);
   } else {
     updateViews.setImageViewResource(R.id.account_icon, type.iconId);
   }
   long amount = a.totalAmount;
   updateViews.setTextViewText(R.id.note, Utils.amountToString(a.currency, amount));
   Utils u = new Utils(context);
   int amountColor = u.getAmountColor(amount);
   updateViews.setTextColor(R.id.note, amountColor);
   addScrollOnClick(context, updateViews, widgetId, providerClass);
   addTapOnClick(context, updateViews);
   addButtonsClick(context, updateViews);
   saveAccountForWidget(context, widgetId, a.id);
   return updateViews;
 }
  @SuppressLint("NewApi")
  @Override
  protected Boolean doInBackground(String... params) {

    // Perform this loop procedure for each App Widget that belongs to this mApp
    for (int i = 0; i < mNumWidgets; i++) {
      currentAppWidgetId = mAppWidgetIds[i];
      String widgetColor = mApp.getSharedPreferences().getString("" + currentAppWidgetId, "DARK");
      views = new RemoteViews(mContext.getPackageName(), R.layout.small_widget_layout);

      if (widgetColor.equals("DARK")) {
        views.setInt(
            R.id.small_widget_parent_layout, "setBackgroundResource", R.drawable.appwidget_dark_bg);
        views.setImageViewResource(
            R.id.app_widget_small_previous, R.drawable.btn_playback_previous_light);
        views.setImageViewResource(R.id.app_widget_small_next, R.drawable.btn_playback_next_light);
      } else if (widgetColor.equals("LIGHT")) {
        views.setInt(
            R.id.small_widget_parent_layout, "setBackgroundResource", R.drawable.appwidget_bg);
        views.setImageViewResource(
            R.id.app_widget_small_previous, R.drawable.btn_playback_previous);
        views.setImageViewResource(R.id.app_widget_small_next, R.drawable.btn_playback_next);
      }

      Intent playPauseIntent = new Intent();
      playPauseIntent.setAction(PLAY_PAUSE_ACTION);
      PendingIntent playPausePendingIntent =
          PendingIntent.getBroadcast(mContext.getApplicationContext(), 0, playPauseIntent, 0);

      Intent nextIntent = new Intent();
      nextIntent.setAction(NEXT_ACTION);
      PendingIntent nextPendingIntent =
          PendingIntent.getBroadcast(mContext.getApplicationContext(), 0, nextIntent, 0);

      Intent previousIntent = new Intent();
      previousIntent.setAction(PREVIOUS_ACTION);
      PendingIntent previousPendingIntent =
          PendingIntent.getBroadcast(mContext.getApplicationContext(), 0, previousIntent, 0);

      // Get the layout of the widget and attach a click listener to each element.
      views.setOnClickPendingIntent(R.id.app_widget_small_play, playPausePendingIntent);
      views.setOnClickPendingIntent(R.id.app_widget_small_previous, previousPendingIntent);
      views.setOnClickPendingIntent(R.id.app_widget_small_next, nextPendingIntent);

      // Get the downsampled image of the current song's album art.
      views.setImageViewBitmap(R.id.app_widget_small_image, getAlbumArt());

      if (mApp.isServiceRunning()) {

        final Intent notificationIntent = new Intent(mContext, NowPlayingActivity.class);
        notificationIntent.putExtra("CALLED_FROM_FOOTER", true);
        notificationIntent.putExtra("CALLED_FROM_NOTIF", true);

        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0);
        views.setOnClickPendingIntent(R.id.app_widget_small_image, pendingIntent);

      } else {
        views.setImageViewResource(R.id.app_widget_small_image, R.drawable.default_album_art);

        if (widgetColor.equals("DARK")) {
          views.setImageViewResource(
              R.id.app_widget_small_play, R.drawable.btn_playback_play_light);
        } else if (widgetColor.equals("LIGHT")) {
          views.setImageViewResource(R.id.app_widget_small_play, R.drawable.btn_playback_play);
        }

        final Intent intent = new Intent(mContext, LauncherActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, intent, 0);
        views.setOnClickPendingIntent(R.id.app_widget_small_image, pendingIntent);
      }

      views.setTextViewText(
          R.id.app_widget_small_line_one, mApp.getService().getCurrentSong().getTitle());
      views.setTextViewText(
          R.id.app_widget_small_line_two,
          mApp.getService().getCurrentSong().getAlbum()
              + mApp.getService().getCurrentSong().getArtist());

      if (widgetColor.equals("LIGHT")) {
        views.setTextColor(R.id.app_widget_small_line_one, Color.BLACK);
        views.setTextColor(R.id.app_widget_small_line_two, Color.BLACK);
      }

      if (mApp.isServiceRunning()) {

        try {
          if (mApp.getService().getCurrentMediaPlayer().isPlaying()) {
            if (widgetColor.equals("DARK")) {
              views.setImageViewResource(
                  R.id.app_widget_small_play, R.drawable.btn_playback_pause_light);
            } else if (widgetColor.equals("LIGHT")) {
              views.setImageViewResource(R.id.app_widget_small_play, R.drawable.btn_playback_pause);
            }

          } else {
            if (widgetColor.equals("DARK")) {
              views.setImageViewResource(
                  R.id.app_widget_small_play, R.drawable.btn_playback_play_light);
            } else if (widgetColor.equals("LIGHT")) {
              views.setImageViewResource(R.id.app_widget_small_play, R.drawable.btn_playback_play);
            }
          }
        } catch (Exception e) {
          // TODO Auto-generated method stub
          e.printStackTrace();
        }
      }

      // Tell the AppWidgetManager to perform an update on the current app widget\
      try {
        mAppWidgetManager.updateAppWidget(currentAppWidgetId, views);
      } catch (Exception e) {
        continue;
      }
    }

    return true;
  }
  private RemoteViews updateRemoteViews(Context context, int widgetId) {
    Setup setup = Setup.load(context, widgetId);

    long now = Calendar.getInstance().getTimeInMillis();
    int daysLeft = DateUtil.daysBetween(now, setup.targetDate);
    int weekDaysLeft = DateUtil.weekDaysBetween(now, setup.targetDate);
    int daysFromStart = DateUtil.daysBetween(setup.startDate, setup.targetDate);
    Log.d(getClass().getSimpleName(), daysLeft + "/" + weekDaysLeft + ", max=" + daysFromStart);

    RemoteViews views = new RemoteViews(context.getPackageName(), layoutId);

    Bitmap backImage =
        BackgroundImageAdapter.createColoredBackground(
            context, setup.backgroundIndex, setup.alpha, backgroundResId);
    views.setImageViewBitmap(R.id.image_back, backImage);

    if (daysLeft > 0) {
      if (setup.showDays.showCalendarDays()) {
        views.setViewVisibility(R.id.text_calendar_days, View.VISIBLE);
        views.setTextViewText(R.id.text_calendar_days, daysLeft + "");
        views.setTextColor(R.id.text_calendar_days, Color.BLACK);
      } else {
        views.setViewVisibility(R.id.text_calendar_days, View.GONE);
      }

      if (setup.showDays.showWeekDays()) {
        views.setViewVisibility(R.id.text_week_days, View.VISIBLE);
        views.setTextViewText(R.id.text_week_days, weekDaysLeft + "");
        views.setTextColor(R.id.text_week_days, Color.rgb(100, 100, 100));
        if (setup.showDays == ShowDaysType.WEEK) {
          views.setFloat(R.id.text_week_days, "setTextSize", 26);
        } else {
          views.setFloat(R.id.text_week_days, "setTextSize", 16);
        }
      } else {
        views.setViewVisibility(R.id.text_week_days, View.GONE);
      }

      if (setup.showEventName) {
        views.setTextViewText(R.id.text_footer, setup.eventName);
      } else {
        if (daysLeft == 1) {
          views.setTextViewText(R.id.text_footer, context.getString(R.string.label_day_left));
        } else {
          views.setTextViewText(R.id.text_footer, context.getString(R.string.label_days_left));
        }
      }

      if (setup.showProgress) {
        views.setViewVisibility(R.id.layout_progress, View.VISIBLE);
        views.setProgressBar(R.id.progress_days, daysFromStart, daysFromStart - daysLeft, false);
      } else {
        views.setViewVisibility(R.id.layout_progress, View.GONE);
      }
    } else {
      views.setViewVisibility(R.id.text_week_days, View.GONE);
      views.setViewVisibility(R.id.layout_progress, View.GONE);

      // check how many days elapsed since the target date
      views.setViewVisibility(R.id.text_calendar_days, View.VISIBLE);
      int daysSince = DateUtil.daysBetween(setup.targetDate, now);
      views.setTextViewText(R.id.text_calendar_days, daysSince + "");

      if (daysSince > 0) {
        views.setTextColor(R.id.text_calendar_days, Color.GRAY); // in the past
      } else {
        views.setTextColor(R.id.text_calendar_days, Color.RED); // today
      }

      if (setup.showEventName) {
        views.setTextViewText(R.id.text_footer, setup.eventName);
      } else {
        if (daysSince <= 0) {
          views.setTextViewText(R.id.text_footer, context.getString(R.string.label_today));
        } else if (daysSince == 1) {
          views.setTextViewText(R.id.text_footer, context.getString(R.string.label_day_since));
        } else {
          views.setTextViewText(R.id.text_footer, context.getString(R.string.label_days_since));
        }
      }
    }

    // configure the click behavior of the widget
    Intent intent = new Intent(context, CountdownPreferences.class);
    // this causes each widget to have a unique PendingIntent
    Uri data = Uri.withAppendedPath(Uri.parse("peregin://widget/id/"), String.valueOf(widgetId));
    intent.setData(data);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widgetId);
    PendingIntent pendingIntent =
        PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    views.setOnClickPendingIntent(R.id.counter_widget, pendingIntent);

    return views;
  }
    public RemoteViews getViewAt(int position) {
      RemoteViews rv;
      boolean isSectionHeader = mHeaderPositionMap.get(position);
      int offset = mPMap.get(position);

      Intent homeIntent = new Intent(mContext, HomeActivity.class);

      if (isSectionHeader) {
        rv = new RemoteViews(mContext.getPackageName(), R.layout.list_item_schedule_header);
        Section section = mSections.get(offset - 1);
        rv.setTextViewText(R.id.list_item_schedule_header_textview, section.getTitle());

      } else {
        int cursorPosition = position - offset;
        mCursor.moveToPosition(cursorPosition);

        rv = new RemoteViews(mContext.getPackageName(), R.layout.list_item_schedule_block_widget);
        final String type = mCursor.getString(BlocksQuery.BLOCK_TYPE);

        final String blockId = mCursor.getString(BlocksQuery.BLOCK_ID);
        final String blockTitle = mCursor.getString(BlocksQuery.BLOCK_TITLE);
        final String blockType = mCursor.getString(BlocksQuery.BLOCK_TYPE);
        final String blockMeta = mCursor.getString(BlocksQuery.BLOCK_META);
        final long blockStart = mCursor.getLong(BlocksQuery.BLOCK_START);
        final long blockEnd = mCursor.getLong(BlocksQuery.BLOCK_END);

        final Resources res = mContext.getResources();
        rv.setTextViewText(R.id.block_endtime, null);

        if (ScheduleContract.Blocks.BLOCK_TYPE_SESSION.equals(type)
            || ScheduleContract.Blocks.BLOCK_TYPE_CODELAB.equals(type)
            || ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS.equals(blockType)) {
          final int numStarredSessions = mCursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS);
          final String starredSessionId = mCursor.getString(BlocksQuery.STARRED_SESSION_ID);

          if (numStarredSessions == 0) {
            // No sessions starred
            rv.setTextViewText(
                R.id.block_title,
                mContext.getString(
                    R.string.schedule_empty_slot_title_template,
                    TextUtils.isEmpty(blockTitle) ? "" : (" " + blockTitle.toLowerCase())));
            rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1_positive));
            rv.setTextViewText(
                R.id.block_subtitle, mContext.getString(R.string.schedule_empty_slot_subtitle));
            rv.setViewVisibility(R.id.extra_button, View.GONE);

            Intent fillIntent =
                TaskStackBuilderProxyActivity.getFillIntent(
                    homeIntent,
                    new Intent(
                        Intent.ACTION_VIEW, ScheduleContract.Blocks.buildSessionsUri(blockId)));
            rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillIntent);

          } else if (numStarredSessions == 1) {
            // exactly 1 session starred
            final String starredSessionTitle = mCursor.getString(BlocksQuery.STARRED_SESSION_TITLE);
            String starredSessionSubtitle =
                mCursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME);
            if (starredSessionSubtitle == null) {
              starredSessionSubtitle = mContext.getString(R.string.unknown_room);
            }

            // Determine if the session is in the past
            long currentTimeMillis = UIUtils.getCurrentTime(mContext);
            boolean conferenceEnded = currentTimeMillis > UIUtils.CONFERENCE_END_MILLIS;
            boolean blockEnded = currentTimeMillis > blockEnd;
            if (blockEnded && !conferenceEnded) {
              starredSessionSubtitle = mContext.getString(R.string.session_finished);
            }

            rv.setTextViewText(R.id.block_title, starredSessionTitle);
            rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1));
            rv.setTextViewText(R.id.block_subtitle, starredSessionSubtitle);
            rv.setViewVisibility(R.id.extra_button, View.VISIBLE);

            Intent fillIntent =
                TaskStackBuilderProxyActivity.getFillIntent(
                    homeIntent,
                    new Intent(
                        Intent.ACTION_VIEW,
                        ScheduleContract.Sessions.buildSessionUri(starredSessionId)));
            rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillIntent);

            fillIntent =
                TaskStackBuilderProxyActivity.getFillIntent(
                    homeIntent,
                    new Intent(
                        Intent.ACTION_VIEW, ScheduleContract.Blocks.buildSessionsUri(blockId)));
            rv.setOnClickFillInIntent(R.id.extra_button, fillIntent);

          } else {
            // 2 or more sessions starred
            rv.setTextViewText(
                R.id.block_title,
                mContext.getString(R.string.schedule_conflict_title, numStarredSessions));
            rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1));
            rv.setTextViewText(
                R.id.block_subtitle, mContext.getString(R.string.schedule_conflict_subtitle));
            rv.setViewVisibility(R.id.extra_button, View.VISIBLE);

            Intent fillIntent =
                TaskStackBuilderProxyActivity.getFillIntent(
                    homeIntent,
                    new Intent(
                        Intent.ACTION_VIEW,
                        ScheduleContract.Blocks.buildStarredSessionsUri(blockId)));
            rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillIntent);

            fillIntent =
                TaskStackBuilderProxyActivity.getFillIntent(
                    homeIntent,
                    new Intent(
                        Intent.ACTION_VIEW, ScheduleContract.Blocks.buildSessionsUri(blockId)));
            rv.setOnClickFillInIntent(R.id.extra_button, fillIntent);
          }
          rv.setTextColor(R.id.block_subtitle, res.getColor(R.color.body_text_2));

        } else if (ScheduleContract.Blocks.BLOCK_TYPE_KEYNOTE.equals(type)) {
          long currentTimeMillis = UIUtils.getCurrentTime(mContext);
          boolean past =
              (currentTimeMillis > blockEnd && currentTimeMillis < UIUtils.CONFERENCE_END_MILLIS);
          boolean present = !past && (currentTimeMillis >= blockStart);
          boolean canViewStream = present && UIUtils.hasHoneycomb();

          final String starredSessionId = mCursor.getString(BlocksQuery.STARRED_SESSION_ID);
          final String starredSessionTitle = mCursor.getString(BlocksQuery.STARRED_SESSION_TITLE);
          rv.setTextViewText(R.id.block_title, starredSessionTitle);
          rv.setTextViewText(R.id.block_subtitle, res.getString(R.string.keynote_room));
          rv.setTextColor(
              R.id.block_title,
              canViewStream
                  ? res.getColor(R.color.body_text_1)
                  : res.getColor(R.color.body_text_disabled));
          rv.setTextColor(
              R.id.block_subtitle,
              canViewStream
                  ? res.getColor(R.color.body_text_2)
                  : res.getColor(R.color.body_text_disabled));
          rv.setViewVisibility(R.id.extra_button, View.GONE);

          rv.setOnClickFillInIntent(R.id.list_item_middle_container, new Intent());
        } else {
          rv.setTextViewText(R.id.block_title, blockTitle);
          rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_disabled));
          rv.setTextViewText(R.id.block_subtitle, blockMeta);
          rv.setTextColor(R.id.block_subtitle, res.getColor(R.color.body_text_disabled));
          rv.setViewVisibility(R.id.extra_button, View.GONE);

          mBuffer.setLength(0);
          rv.setTextViewText(
              R.id.block_endtime,
              DateUtils.formatDateRange(
                      mContext,
                      mFormatter,
                      blockEnd,
                      blockEnd,
                      DateUtils.FORMAT_SHOW_TIME,
                      PrefUtils.getDisplayTimeZone(mContext).getID())
                  .toString());

          rv.setOnClickFillInIntent(R.id.list_item_middle_container, new Intent());
        }

        mBuffer.setLength(0);
        rv.setTextViewText(
            R.id.block_time,
            DateUtils.formatDateRange(
                    mContext,
                    mFormatter,
                    blockStart,
                    blockStart,
                    DateUtils.FORMAT_SHOW_TIME,
                    PrefUtils.getDisplayTimeZone(mContext).getID())
                .toString());
      }

      return rv;
    }
  private void updateWidgetContent(
      Context context,
      AppWidgetManager appWidgetManager,
      int[] widgetIds,
      RemoteViews remoteViews) {

    Log.d(TAG, "Updating TodoWidgetProvider content.");

    // get widget ID's if not provided
    if (widgetIds == null) {
      widgetIds =
          appWidgetManager.getAppWidgetIds(
              new ComponentName(context, TodoWidgetProvider.class.getName()));
    }

    // get remoteViews if not provided
    if (remoteViews == null) {
      remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget);
    }

    // get taskBag from application
    TaskBag taskBag = ((TodoApplication) ((ContextWrapper) context).getBaseContext()).getTaskBag();

    List<Task> tasks = taskBag.getTasks();
    int taskCount = tasks.size();
    Resources resources = context.getResources();

    for (int i = 0; i < TASKS_TO_DISPLAY; i++) {
      // get task to display
      if (i >= tasks.size()) {
        // no more tasks to display
        remoteViews.setViewVisibility(id[i][TASK_ID], View.GONE);
        remoteViews.setViewVisibility(id[i][TASK_PRIO], View.GONE);
        remoteViews.setViewVisibility(id[i][TASK_TEXT], View.GONE);
        continue;
      }
      Task task = tasks.get(i);

      if (!task.isCompleted()) { // don't show completed tasks
        // text
        String taskText;
        if (task.inScreenFormat().length() > 33) {
          taskText = task.inScreenFormat().substring(0, 33) + "...";
        } else {
          taskText = task.inScreenFormat();
        }
        SpannableString ss = new SpannableString(taskText);
        remoteViews.setTextViewText(id[i][TASK_TEXT], ss);
        remoteViews.setViewVisibility(id[i][TASK_TEXT], View.VISIBLE);

        // priority
        int color = R.color.white;
        switch (task.getPriority()) {
          case A:
            color = R.color.green;
            break;
          case B:
            color = R.color.blue;
            break;
          case C:
            color = R.color.orange;
            break;
          case D:
            color = R.color.gold;
          default:
            break;
        }

        remoteViews.setTextViewText(id[i][TASK_PRIO], task.getPriority().inListFormat());
        remoteViews.setTextColor(id[i][TASK_PRIO], resources.getColor(color));
        remoteViews.setViewVisibility(id[i][TASK_PRIO], View.VISIBLE);
      }
    }

    remoteViews.setViewVisibility(R.id.empty, taskCount == 0 ? View.VISIBLE : View.GONE);

    appWidgetManager.updateAppWidget(widgetIds, remoteViews);
  }
Exemple #18
0
  private static void setupViews(
      RemoteViews rv, Context context, MusicDirectory.Entry song, boolean playing) {

    // Use the same text for the ticker and the expanded notification
    String title = song.getTitle();
    String arist = song.getArtist();
    String album = song.getAlbum();

    // Set the album art.
    try {
      int size = context.getResources().getDrawable(R.drawable.unknown_album).getIntrinsicHeight();
      Bitmap bitmap = FileUtil.getAlbumArtBitmap(context, song, size);
      if (bitmap == null) {
        // set default album art
        rv.setImageViewResource(R.id.notification_image, R.drawable.unknown_album);
      } else {
        rv.setImageViewBitmap(R.id.notification_image, bitmap);
      }
    } catch (Exception x) {
      Log.w(TAG, "Failed to get notification cover art", x);
      rv.setImageViewResource(R.id.notification_image, R.drawable.unknown_album);
    }

    // set the text for the notifications
    rv.setTextViewText(R.id.notification_title, title);
    rv.setTextViewText(R.id.notification_artist, arist);
    rv.setTextViewText(R.id.notification_album, album);

    Pair<Integer, Integer> colors = getNotificationTextColors(context);
    if (colors.getFirst() != null) {
      rv.setTextColor(R.id.notification_title, colors.getFirst());
    }
    if (colors.getSecond() != null) {
      rv.setTextColor(R.id.notification_artist, colors.getSecond());
    }

    if (!playing) {
      rv.setImageViewResource(R.id.control_pause, R.drawable.notification_play);
      rv.setImageViewResource(R.id.control_previous, R.drawable.notification_stop);
    }

    // Create actions for media buttons
    PendingIntent pendingIntent;
    if (playing) {
      Intent prevIntent = new Intent("KEYCODE_MEDIA_PREVIOUS");
      prevIntent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
      prevIntent.putExtra(
          Intent.EXTRA_KEY_EVENT,
          new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PREVIOUS));
      pendingIntent = PendingIntent.getService(context, 0, prevIntent, 0);
      rv.setOnClickPendingIntent(R.id.control_previous, pendingIntent);
    } else {
      Intent prevIntent = new Intent("KEYCODE_MEDIA_STOP");
      prevIntent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
      prevIntent.putExtra(
          Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_STOP));
      pendingIntent = PendingIntent.getService(context, 0, prevIntent, 0);
      rv.setOnClickPendingIntent(R.id.control_previous, pendingIntent);
    }

    Intent pauseIntent = new Intent("KEYCODE_MEDIA_PLAY_PAUSE");
    pauseIntent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
    pauseIntent.putExtra(
        Intent.EXTRA_KEY_EVENT,
        new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE));
    pendingIntent = PendingIntent.getService(context, 0, pauseIntent, 0);
    rv.setOnClickPendingIntent(R.id.control_pause, pendingIntent);

    Intent nextIntent = new Intent("KEYCODE_MEDIA_NEXT");
    nextIntent.setComponent(new ComponentName(context, DownloadServiceImpl.class));
    nextIntent.putExtra(
        Intent.EXTRA_KEY_EVENT, new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_NEXT));
    pendingIntent = PendingIntent.getService(context, 0, nextIntent, 0);
    rv.setOnClickPendingIntent(R.id.control_next, pendingIntent);
  }
Exemple #19
0
    @SuppressWarnings("nls")
    public RemoteViews buildUpdate(Context context, int widgetId) {
      DependencyInjectionService.getInstance().inject(this);

      RemoteViews views = null;

      views = new RemoteViews(context.getPackageName(), R.layout.widget_initialized);

      int[] textIDs = TEXT_IDS;
      int[] separatorIDs = SEPARATOR_IDS;
      int numberOfTasks = 5;

      for (int i = 0; i < textIDs.length; i++) views.setTextViewText(textIDs[i], "");

      TodorooCursor<Task> cursor = null;
      Filter filter = null;
      try {
        filter = getFilter(widgetId);
        views.setTextViewText(R.id.widget_title, filter.title);

        SharedPreferences publicPrefs = AstridPreferences.getPublicPrefs(this);
        int flags = publicPrefs.getInt(SortHelper.PREF_SORT_FLAGS, 0);
        int sort = publicPrefs.getInt(SortHelper.PREF_SORT_SORT, 0);
        String query =
            SortHelper.adjustQueryForFlagsAndSort(filter.sqlQuery, flags, sort)
                    .replaceAll("LIMIT \\d+", "")
                + " LIMIT "
                + numberOfTasks;

        database.openForReading();
        cursor =
            taskService.fetchFiltered(
                query, null, Task.ID, Task.TITLE, Task.DUE_DATE, Task.COMPLETION_DATE);
        Task task = new Task();
        for (int i = 0; i < cursor.getCount() && i < numberOfTasks; i++) {
          cursor.moveToPosition(i);
          task.readFromCursor(cursor);

          String textContent = "";
          int textColor = Color.WHITE;

          textContent = task.getValue(Task.TITLE);

          if (task.isCompleted())
            textColor = context.getResources().getColor(R.color.task_list_done);
          else if (task.hasDueDate() && task.getValue(Task.DUE_DATE) < DateUtilities.now())
            textColor = context.getResources().getColor(R.color.task_list_overdue);

          if (i > 0) views.setViewVisibility(separatorIDs[i - 1], View.VISIBLE);
          views.setTextViewText(textIDs[i], textContent);
          views.setTextColor(textIDs[i], textColor);
        }

        for (int i = cursor.getCount() - 1; i < separatorIDs.length; i++) {
          if (i >= 0) views.setViewVisibility(separatorIDs[i], View.INVISIBLE);
        }
      } catch (Exception e) {
        // can happen if database is not ready
        Log.e("WIDGET-UPDATE", "Error updating widget", e);
      } finally {
        if (cursor != null) cursor.close();
      }

      updateForScreenSize(views);

      Intent listIntent = new Intent(context, TaskListActivity.class);
      String customIntent =
          Preferences.getStringValue(WidgetConfigActivity.PREF_CUSTOM_INTENT + widgetId);
      if (customIntent != null) {
        listIntent.setComponent(ComponentName.unflattenFromString(customIntent));
        String serializedExtras =
            Preferences.getStringValue(WidgetConfigActivity.PREF_CUSTOM_EXTRAS + widgetId);
        Bundle extras = AndroidUtilities.bundleFromSerializedString(serializedExtras);
        listIntent.putExtras(extras);
      }
      listIntent.putExtra(TaskListActivity.TOKEN_SOURCE, Constants.SOURCE_WIDGET);
      listIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
      if (filter != null) {
        listIntent.putExtra(TaskListActivity.TOKEN_FILTER, filter);
        listIntent.setAction("L" + widgetId + filter.sqlQuery);
      }
      PendingIntent pendingIntent =
          PendingIntent.getActivity(
              context, widgetId, listIntent, PendingIntent.FLAG_CANCEL_CURRENT);
      views.setOnClickPendingIntent(R.id.taskbody, pendingIntent);

      Intent editIntent = new Intent(context, TaskEditActivity.class);
      editIntent.setFlags(
          Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
      if (filter != null && filter.valuesForNewTasks != null) {
        String values = AndroidUtilities.contentValuesToSerializedString(filter.valuesForNewTasks);
        editIntent.putExtra(TaskEditActivity.TOKEN_VALUES, values);
        editIntent.setType(values);
      }
      pendingIntent = PendingIntent.getActivity(context, 0, editIntent, 0);
      views.setOnClickPendingIntent(R.id.widget_button, pendingIntent);

      return views;
    }
  public static RemoteViews configureItem(
      RemoteViews rv, Task task, Context context, int listId, boolean isMinimal, int widgetId) {
    Intent openIntent = new Intent(context, MainActivity.class);
    openIntent.setAction(MainActivity.SHOW_TASK);
    openIntent.putExtra(MainActivity.EXTRA_ID, task.getId());
    openIntent.setData(Uri.parse(openIntent.toUri(Intent.URI_INTENT_SCHEME)));
    PendingIntent pOpenIntent = PendingIntent.getActivity(context, 0, openIntent, 0);

    rv.setOnClickPendingIntent(R.id.tasks_row, pOpenIntent);
    rv.setOnClickPendingIntent(R.id.tasks_row_name, pOpenIntent);
    if (isMinimal) {
      if (task.getDue() != null) {
        rv.setTextViewText(R.id.tasks_row_due, DateTimeHelper.formatDate(context, task.getDue()));
      } else {
        rv.setViewVisibility(R.id.tasks_row_due, View.GONE);
      }
      rv.setInt(
          R.id.tasks_row_priority,
          "setBackgroundColor",
          TaskHelper.getPrioColor(task.getPriority(), context));
    }
    rv.setTextColor(R.id.tasks_row_name, WidgetHelper.getFontColor(context, widgetId));
    rv.setTextColor(R.id.tasks_row_due, WidgetHelper.getFontColor(context, widgetId));
    rv.setTextViewText(R.id.tasks_row_name, task.getName());
    if (task.isDone()) {
      rv.setTextColor(R.id.tasks_row_name, context.getResources().getColor(R.color.Grey));
    } else {
      /*
       * Is this meaningful? I mean the widget is transparent…
       * rv.setTextColor( R.id.tasks_row_name, context.getResources()
       * .getColor( preferences.getBoolean("darkWidget", false) ?
       * R.color.White : R.color.Black));
       */
    }
    if (!isMinimal) {

      rv.setTextViewText(R.id.tasks_row_priority, task.getPriority() + "");
      rv.setTextColor(R.id.tasks_row_priority, context.getResources().getColor(R.color.Black));
      GradientDrawable drawable =
          (GradientDrawable) context.getResources().getDrawable(R.drawable.priority_rectangle);
      drawable.setColor(TaskHelper.getPrioColor(task.getPriority(), context));
      Bitmap bitmap = Bitmap.createBitmap(40, 40, Config.ARGB_8888);
      Canvas canvas = new Canvas(bitmap);
      drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
      drawable.draw(canvas);
      rv.setImageViewBitmap(R.id.label_bg, bitmap);

      if (listId <= 0) {
        rv.setViewVisibility(R.id.tasks_row_list_name, View.VISIBLE);
        rv.setTextViewText(R.id.tasks_row_list_name, task.getList().getName());
      } else {
        rv.setViewVisibility(R.id.tasks_row_list_name, View.GONE);
      }
      if (task.getContent().length() != 0
          || task.getSubtaskCount() > 0
          || task.getFiles().size() > 0) {
        rv.setViewVisibility(R.id.tasks_row_has_content, View.VISIBLE);
      } else {
        rv.setViewVisibility(R.id.tasks_row_has_content, View.GONE);
      }

      if (task.getDue() != null) {
        rv.setViewVisibility(R.id.tasks_row_due, View.VISIBLE);

        rv.setTextViewText(R.id.tasks_row_due, DateTimeHelper.formatDate(context, task.getDue()));
        if (!isMinimal) {
          rv.setTextColor(
              R.id.tasks_row_due,
              context
                  .getResources()
                  .getColor(TaskHelper.getTaskDueColor(task.getDue(), task.isDone())));
        }
      } else {
        rv.setViewVisibility(R.id.tasks_row_due, View.GONE);
      }
    }
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
      rv.setTextColor(
          R.id.tasks_row_name,
          context
              .getResources()
              .getColor(WidgetHelper.isDark(context, widgetId) ? R.color.White : R.color.Black));
    }
    return rv;
  }
  public static void updateItemView(
      Context context, Cursor cursor, RemoteViews rv, DateFormat mTimeFormat) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean customColors =
        prefs.getBoolean(context.getString(R.string.use_custom_colors_key), false);

    rv.setTextViewText(R.id.city_text, cursor.getString(cursor.getColumnIndex(Clocks.CITY)));

    String id = cursor.getString(cursor.getColumnIndex(Clocks.TIMEZONE_ID));
    if (SANS_JELLY_BEAN_MR1) {
      Date date = new Date();
      TimeZone tz = TimeZone.getTimeZone(id);
      rv.setTextViewText(R.id.time_text, TimeZoneInfo.showTime(tz, date, mTimeFormat, true));
    } else {
      RemoteViewUtil.setTextClockTimeZone(rv, R.id.time_text, id);
    }

    rv.setTextViewText(
        R.id.condition_text, cursor.getString(cursor.getColumnIndex(Clocks.WEATHER_CONDITION)));

    String temperature = BindHelper.getTemperature(context, cursor, false);
    rv.setTextViewText(R.id.temp_text, temperature);

    int condCode = cursor.getInt(cursor.getColumnIndex(Clocks.CONDITION_CODE));
    double lat = cursor.getDouble(cursor.getColumnIndex(Clocks.LATITUDE));
    double lon = cursor.getDouble(cursor.getColumnIndex(Clocks.LONGITUDE));
    if (!customColors) {
      rv.setImageViewResource(R.id.condition_image, WeatherIcons.getIcon(condCode, lon, lat));
    }

    if (customColors) {
      int color = prefs.getInt(context.getString(R.string.background_color_key), Color.BLACK);
      RemoteViewUtil.setBackgroundColor(rv, R.id.widget_item, color);

      int foreground = prefs.getInt(context.getString(R.string.foreground_color_key), Color.WHITE);
      rv.setTextColor(R.id.city_text, foreground);
      rv.setTextColor(R.id.time_text, foreground);
      rv.setTextColor(R.id.condition_text, foreground);
      rv.setTextColor(R.id.temp_text, foreground);

      int res = WeatherIcons.getIcon(condCode, lon, lat);
      if (foreground != Color.WHITE) {
        Drawable drawable = context.getResources().getDrawable(res);
        Bitmap bmp =
            Bitmap.createBitmap(
                drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
        drawable.setColorFilter(foreground, Mode.MULTIPLY);
        Canvas canvas = new Canvas(bmp);
        drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable.draw(canvas);
        drawable.setColorFilter(null);
        rv.setImageViewBitmap(R.id.condition_image, bmp);
      } else {
        rv.setImageViewResource(R.id.condition_image, WeatherIcons.getIcon(condCode, lon, lat));
      }
    } else {
      RemoteViewUtil.setBackground(rv, R.id.widget_item, R.drawable.appwidget_dark_bg);

      int defaultColor = 0xffbebebe;
      rv.setTextColor(R.id.city_text, Color.WHITE);
      rv.setTextColor(R.id.time_text, defaultColor);
      rv.setTextColor(R.id.condition_text, defaultColor);
      rv.setTextColor(R.id.temp_text, Color.WHITE);
    }
  }
  /**
   * Update a single widget.
   *
   * @param context {@link Context}
   * @param appWidgetManager {@link AppWidgetManager}
   * @param appWidgetId id of widget
   */
  static void updateWidget(
      final Context context, final AppWidgetManager appWidgetManager, final int appWidgetId) {
    Log.d(TAG, "updateWidget(" + appWidgetId + ")");
    final SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);
    final long pid = p.getLong(WIDGET_PLANID + appWidgetId, -1L);
    final boolean showShortname = p.getBoolean(WIDGET_SHORTNAME + appWidgetId, false);
    final boolean showCost = p.getBoolean(WIDGET_COST + appWidgetId, false);
    final boolean showBillPeriod = p.getBoolean(WIDGET_BILLPERIOD + appWidgetId, false);
    final boolean showIcon = p.getBoolean(WIDGET_ICON + appWidgetId, false);
    final boolean smallWidget = p.getBoolean(WIDGET_SMALL + appWidgetId, false);
    final Float statsTextSize =
        p.getFloat(WIDGET_STATS_TEXTSIZE + appWidgetId, StatsAppWidgetConfigure.DEFAULT_TEXTSIZE);
    final Float planTextSize =
        p.getFloat(WIDGET_PLAN_TEXTSIZE + appWidgetId, StatsAppWidgetConfigure.DEFAULT_TEXTSIZE);
    final int textColor =
        p.getInt(WIDGET_TEXTCOLOR + appWidgetId, StatsAppWidgetConfigure.DEFAULT_TEXTCOLOR);
    final int bgColor =
        p.getInt(WIDGET_BGCOLOR + appWidgetId, StatsAppWidgetConfigure.DEFAULT_BGCOLOR);
    Log.d(TAG, "planid: " + pid);
    final ContentResolver cr = context.getContentResolver();

    if (pid < 0L) {
      return;
    }
    final long ppid = DataProvider.Plans.getParent(cr, pid);
    long bid = -1L;
    String pname = null;
    float cpp = 0F;
    int ltype = DataProvider.LIMIT_TYPE_NONE;
    long limit = 0L;
    int ptype = -1;
    String where;
    int upc, upm, ups;
    boolean isMerger;
    String billdayWhere = null;
    Cursor cursor =
        cr.query(
            DataProvider.Plans.CONTENT_URI,
            DataProvider.Plans.PROJECTION,
            DataProvider.Plans.ID + " = ?",
            new String[] {String.valueOf(pid)},
            null);
    if (cursor.moveToFirst()) {
      if (showShortname) {
        pname = cursor.getString(DataProvider.Plans.INDEX_SHORTNAME);
      } else {
        pname = cursor.getString(DataProvider.Plans.INDEX_NAME);
      }
      ptype = cursor.getInt(DataProvider.Plans.INDEX_TYPE);
      bid = cursor.getLong(DataProvider.Plans.INDEX_BILLPERIOD_ID);
      ltype = cursor.getInt(DataProvider.Plans.INDEX_LIMIT_TYPE);
      limit =
          DataProvider.Plans.getLimit(ptype, ltype, cursor.getLong(DataProvider.Plans.INDEX_LIMIT));
      upc = cursor.getInt(DataProvider.Plans.INDEX_MIXED_UNITS_CALL);
      upm = cursor.getInt(DataProvider.Plans.INDEX_MIXED_UNITS_MMS);
      ups = cursor.getInt(DataProvider.Plans.INDEX_MIXED_UNITS_SMS);
      cpp = cursor.getFloat(DataProvider.Plans.INDEX_COST_PER_PLAN);

      final String s = cursor.getString(DataProvider.Plans.INDEX_MERGED_PLANS);
      where = DataProvider.Plans.parseMergerWhere(pid, s);
      if (s == null || s.length() == 0) {
        isMerger = false;
      } else {
        isMerger = true;
      }
    } else {
      return;
    }
    cursor.close();

    int bpos = 0;
    int bmax = -1;
    if (bid >= 0L) {
      cursor =
          cr.query(
              DataProvider.Plans.CONTENT_URI,
              DataProvider.Plans.PROJECTION,
              DataProvider.Plans.ID + " = ?",
              new String[] {String.valueOf(bid)},
              null);
      if (cursor.moveToFirst()) {
        final int bp = cursor.getInt(DataProvider.Plans.INDEX_BILLPERIOD);
        final long bday = cursor.getLong(DataProvider.Plans.INDEX_BILLDAY);
        billdayWhere = DataProvider.Plans.getBilldayWhere(bp, bday, null);
        if (showBillPeriod && bp != DataProvider.BILLPERIOD_INFINITE) {
          Calendar billDay = Calendar.getInstance();
          billDay.setTimeInMillis(bday);
          billDay = DataProvider.Plans.getBillDay(bp, billDay, null, false);
          final Calendar nextBillDay = DataProvider.Plans.getBillDay(bp, billDay, null, true);

          final long pr = billDay.getTimeInMillis() / CallMeter.MILLIS;
          final long nx =
              (nextBillDay.getTimeInMillis() // .
                      / CallMeter.MILLIS)
                  - pr;
          long nw = System.currentTimeMillis();
          nw = (nw / CallMeter.MILLIS) - pr;

          bmax = (int) nx;
          bpos = (int) nw;
        }
      }
      cursor.close();
    }
    Log.d(TAG, "bpos/bmax: " + bpos + "/" + bmax);
    billdayWhere = DbUtils.sqlAnd(billdayWhere, where);

    int used = 0;
    PlanStatus ps =
        PlanStatus.get(
            cr, billdayWhere, isMerger && ptype == DataProvider.TYPE_MIXED, upc, upm, ups);

    if (ps == null) {
      ps = new PlanStatus();
    } else {
      Log.d(TAG, "plan: " + pid);
      Log.d(TAG, "count: " + ps.count);
      Log.d(TAG, "cost: " + ps.cost);
      Log.d(TAG, "billedAmount: " + ps.billedAmount);
      used = DataProvider.Plans.getUsed(ptype, ltype, ps.billedAmount, ps.cost);
    }
    if (ppid >= 0L) {
      ps.cost = 0F;
    } else {
      ps.cost += cpp;
    }

    String stats =
        Plans.formatAmount(ptype, ps.billedAmount, p.getBoolean(Preferences.PREFS_SHOWHOURS, true));
    if (ptype == DataProvider.TYPE_CALL) {
      stats += " (" + ps.count + ")";
    }
    if (limit > 0) {
      stats += "\n" + (used * CallMeter.HUNDRET / limit) + "%";
    }
    if (showCost && ps.cost > 0F) {
      stats += "\n" + String.format(Preferences.getCurrencyFormat(context), ps.cost);
    }

    Log.d(TAG, "limit: " + limit);
    Log.d(TAG, "used: " + used);
    Log.d(TAG, "stats: " + stats);

    final int widgetLayout =
        smallWidget ? R.layout.stats_appwidget_small : R.layout.stats_appwidget;
    final RemoteViews views = new RemoteViews(context.getPackageName(), widgetLayout);
    views.setImageViewBitmap(R.id.widget_bg, getBackground(bgColor, bmax, bpos, limit, used));
    views.setTextViewText(R.id.plan, pname);
    views.setTextViewText(R.id.stats, stats);
    views.setFloat(R.id.plan, "setTextSize", planTextSize);
    views.setFloat(R.id.stats, "setTextSize", statsTextSize);
    views.setTextColor(R.id.plan, textColor);
    views.setTextColor(R.id.stats, textColor);
    views.setOnClickPendingIntent(
        R.id.widget, PendingIntent.getActivity(context, 0, new Intent(context, Plans.class), 0));
    if (showIcon) {
      views.setViewVisibility(R.id.widget_icon, android.view.View.VISIBLE);
      switch (ptype) {
        case DataProvider.TYPE_DATA:
          views.setImageViewResource(R.id.widget_icon, R.drawable.data);
          break;
        case DataProvider.TYPE_CALL:
          views.setImageViewResource(R.id.widget_icon, R.drawable.phone);
          break;
        case DataProvider.TYPE_SMS:
        case DataProvider.TYPE_MMS:
          views.setImageViewResource(R.id.widget_icon, R.drawable.message);
          break;
        case DataProvider.TYPE_MIXED:
          views.setImageViewResource(R.id.widget_icon, R.drawable.phone);
          break;
      }
    }

    appWidgetManager.updateAppWidget(appWidgetId, views);
  }
 @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
 public void widget4_4Setting(RemoteViews views, AppWidgetManager manager, Bitmap bitmap) {
   Intent main4 = new Intent(Common.ACTION_HOME4_4);
   PendingIntent mainP4 = PendingIntent.getBroadcast(this, 0, main4, 0);
   views.setOnClickPendingIntent(R.id.btHome, mainP4);
   Intent home = new Intent(Common.ACTION_HOME4_4);
   PendingIntent dialP = PendingIntent.getBroadcast(this, 0, home, 0);
   views.setOnClickPendingIntent(R.id.ivWeek, dialP);
   Intent month4 = new Intent(Common.ACTION_MONTH4_4);
   PendingIntent monthP4 = PendingIntent.getBroadcast(this, 0, month4, 0);
   views.setOnClickPendingIntent(R.id.btMonth, monthP4);
   Intent week4 = new Intent(Common.ACTION_WEEK4_4);
   PendingIntent weekP4 = PendingIntent.getBroadcast(this, 0, week4, 0);
   views.setOnClickPendingIntent(R.id.btWeek, weekP4);
   Intent back4 = new Intent(Common.ACTION_BACK4_4);
   PendingIntent backP4 = PendingIntent.getBroadcast(this, 0, back4, 0);
   views.setOnClickPendingIntent(R.id.btBack, backP4);
   Intent forward4 = new Intent(Common.ACTION_FORWARD4_4);
   PendingIntent forwardP4 = PendingIntent.getBroadcast(this, 0, forward4, 0);
   views.setOnClickPendingIntent(R.id.btForward, forwardP4);
   if (viewMode != 0) {
     for (int i = 0; i < 42; i++) {
       int llID = getResources().getIdentifier("ll" + i, "id", "com.daemin.timetable");
       int tvID = getResources().getIdentifier("tv" + i, "id", "com.daemin.timetable");
       if (i >= Dates.NOW.dayOfWeek + 1 && i < Dates.NOW.dayOfWeek + Dates.NOW.dayNumOfMonth + 1) {
         Intent in = new Intent(this, DialSchedule.class);
         in.putExtra("widgetFlag", true);
         in.putExtra("widget4_4", true);
         in.putExtra("dayCnt", i);
         in.putExtra("day", Dates.NOW.mData[i]);
         PendingIntent dP =
             PendingIntent.getActivity(this, i + 200, in, PendingIntent.FLAG_UPDATE_CURRENT);
         views.setOnClickPendingIntent(llID, dP);
         if (Dates.NOW.isToday) {
           if (i == Dates.NOW.dayOfMonth + Dates.NOW.dayOfWeek) {
             views.setInt(llID, "setBackgroundResource", R.color.transmaincolor);
           }
         } else {
           views.setInt(llID, "setBackgroundResource", R.drawable.bt_click);
         }
         int j = i % 7;
         switch (j) {
           case 0:
             views.setTextColor(tvID, getResources().getColor(R.color.red));
             break;
           case 6:
             views.setTextColor(tvID, getResources().getColor(R.color.blue));
             break;
           default:
             views.setTextColor(tvID, getResources().getColor(android.R.color.black));
             break;
         }
         views.setTextViewText(tvID, Dates.NOW.mData[i]);
       } else { // 달력에서 월에 해당하는 날짜 이외의 날짜들은 회색으로 표시
         Intent in = new Intent(Common.ACTION_DUMMY4_4);
         PendingIntent dP = PendingIntent.getBroadcast(this, 0, in, 0);
         views.setOnClickPendingIntent(llID, dP);
         views.setTextViewText(tvID, Dates.NOW.mData[i]);
         views.setTextColor(tvID, getResources().getColor(R.color.middlegray));
         views.setInt(llID, "setBackgroundResource", android.R.color.white);
       }
     }
     fetchMonthData(views);
   }
   for (int appWidgetId : manager.getAppWidgetIds(new ComponentName(this, Widget4_4.class))) {
     manager.updateAppWidget(appWidgetId, views);
   }
   if (bitmap != null) bitmap.recycle();
 }