Java Code Examples for android.widget.RemoteViews#setInt()

The following examples show how to use android.widget.RemoteViews#setInt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WideWidget.java    From Jockey with Apache License 2.0 6 votes vote down vote up
private RemoteViews createBaseView(Context context) {
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_wide);

    Intent launcherIntent = LibraryActivity.newNowPlayingIntent(context);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, launcherIntent, 0);
    views.setOnClickPendingIntent(R.id.widget_wide_container, pendingIntent);

    views.setOnClickPendingIntent(R.id.widget_next, getSkipNextIntent(context));
    views.setOnClickPendingIntent(R.id.widget_play_pause, getPlayPauseIntent(context));
    views.setOnClickPendingIntent(R.id.widget_previous, getSkipPreviousIntent(context));

    @ColorInt int buttonColor = ContextCompat.getColor(context, R.color.widget_button);

    views.setInt(R.id.widget_next, "setColorFilter", buttonColor);
    views.setInt(R.id.widget_play_pause, "setColorFilter", buttonColor);
    views.setInt(R.id.widget_previous, "setColorFilter", buttonColor);

    return views;
}
 
Example 2
Source File: CompactWidget.java    From Jockey with Apache License 2.0 6 votes vote down vote up
private RemoteViews createBaseView(Context context) {
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_compact);

    Intent launcherIntent = LibraryActivity.newNowPlayingIntent(context);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, launcherIntent, 0);
    views.setOnClickPendingIntent(R.id.widget_compact_container, pendingIntent);

    views.setOnClickPendingIntent(R.id.widget_next, getSkipNextIntent(context));
    views.setOnClickPendingIntent(R.id.widget_play_pause, getPlayPauseIntent(context));
    views.setOnClickPendingIntent(R.id.widget_previous, getSkipPreviousIntent(context));

    @ColorInt int buttonColor = ContextCompat.getColor(context, R.color.widget_button);

    views.setInt(R.id.widget_next, "setColorFilter", buttonColor);
    views.setInt(R.id.widget_play_pause, "setColorFilter", buttonColor);
    views.setInt(R.id.widget_previous, "setColorFilter", buttonColor);

    return views;
}
 
Example 3
Source File: ControlWidget.java    From BlueSound with The Unlicense 6 votes vote down vote up
static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                            int appWidgetId) {

    // Create an Intent to launch ExampleActivity
    //Intent intent = BlueService.getToggleIntent(context);
    //PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    //
    Intent intent = new Intent(context, BlueToggleReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 234324243, intent, 0);

    //CharSequence widgetText = context.getString(R.string.appwidget_text);
    // Construct the RemoteViews object
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.control_widget);
    //Check if ON or if OFF
    if( BluetoothManager.getInstance().getStatus() ){
        views.setInt(R.id.widget_master, "setBackgroundResource",R.drawable.ic_audio_off );
    }else{
        views.setInt(R.id.widget_master, "setBackgroundResource",R.drawable.ic_audio_on );
    }

    views.setOnClickPendingIntent(R.id.widget_master, pendingIntent);

    // Instruct the widget manager to update the widget
    appWidgetManager.updateAppWidget(appWidgetId, views);

}
 
Example 4
Source File: ExtLocationWidgetProvider.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
public static void setWidgetTheme(Context context, RemoteViews remoteViews) {
    appendLog(context, TAG, "setWidgetTheme:start");
    int textColorId = AppPreference.getTextColor(context);
    int backgroundColorId = AppPreference.getWidgetBackgroundColor(context);
    int windowHeaderBackgroundColorId = AppPreference.getWindowHeaderBackgroundColorId(context);

    remoteViews.setInt(R.id.widget_ext_loc_3x3_widget_root, "setBackgroundColor", backgroundColorId);
    remoteViews.setTextColor(R.id.widget_ext_loc_3x3_widget_temperature, textColorId);
    remoteViews.setTextColor(R.id.widget_ext_loc_3x3_widget_description, textColorId);
    remoteViews.setTextColor(R.id.widget_ext_loc_3x3_widget_description, textColorId);
    remoteViews.setTextColor(R.id.widget_ext_loc_3x3_widget_second_temperature, textColorId);
    remoteViews.setInt(R.id.widget_ext_loc_3x3_header_layout, "setBackgroundColor", windowHeaderBackgroundColorId);
    appendLog(context, TAG, "setWidgetTheme:end");
}
 
Example 5
Source File: TodayWidgetProvider.java    From ETSMobile-Android2 with Apache License 2.0 5 votes vote down vote up
private void setUpSyncBtn(RemoteViews views, int textColor) {
    Intent intentRefresh = getUpdateIntent();
    PendingIntent pendingIntentRefresh = PendingIntent.getBroadcast(context, SYNC_REQUEST_CODE,
            intentRefresh, PendingIntent.FLAG_UPDATE_CURRENT);

    views.setInt(syncBtnId, "setColorFilter", textColor);
    views.setInt(syncBtnId, "setBackgroundColor", Color.TRANSPARENT);
    views.setOnClickPendingIntent(syncBtnId, pendingIntentRefresh);
}
 
Example 6
Source File: SimpleWidgetProvider.java    From OmniList with GNU Affero General Public License v3.0 5 votes vote down vote up
private void configToolbar(Context context, RemoteViews views, SparseArray<PendingIntent> pendingIntentsMap) {
    views.setOnClickPendingIntent(R.id.iv_launch_app, pendingIntentsMap.get(R.id.iv_launch_app));
    views.setOnClickPendingIntent(R.id.iv_add_record, pendingIntentsMap.get(R.id.iv_add_record));
    views.setOnClickPendingIntent(R.id.iv_add_mind, pendingIntentsMap.get(R.id.iv_add_mind));
    views.setOnClickPendingIntent(R.id.iv_add_photo, pendingIntentsMap.get(R.id.iv_add_photo));
    views.setOnClickPendingIntent(R.id.iv_add_sketch, pendingIntentsMap.get(R.id.iv_add_sketch));
    views.setOnClickPendingIntent(R.id.iv_setting, pendingIntentsMap.get(R.id.iv_setting));
    views.setInt(R.id.toolbar, "setBackgroundColor", ColorUtils.fadeColor(ColorUtils.primaryColor(), 0.2f));
}
 
Example 7
Source File: ListRemoteViewsFactory.java    From OmniList with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public RemoteViews getViewAt(int position) {
    RemoteViews row = new RemoteViews(app.getPackageName(), R.layout.widget_item_assignment);

    Assignment assignment = assignmentList.get(position);

    row.setTextViewText(R.id.tv_title, assignment.getName());

    row.setImageViewResource(R.id.iv_priority, assignment.getPriority().iconRes);

    row.setImageViewResource(R.id.iv_completed, assignment.getProgress() == Constants.MAX_ASSIGNMENT_PROGRESS ?
            R.drawable.ic_check_box_black_24dp :
            R.drawable.ic_check_box_outline_blank_black_24dp);

    row.setTextViewText(R.id.tv_time_info,
            PalmApp.getStringCompact(R.string.text_last_modified_time) + ":"
                    + TimeUtils.getLongDateTime(app.getApplicationContext(), assignment.getLastModifiedTime()));
    row.setInt(R.id.root, "setBackgroundColor", app.getResources().getColor(R.color.white_translucent));
    row.setViewVisibility(R.id.iv_files, assignment.getAttachments() != 0 ? View.VISIBLE : View.GONE);
    row.setViewVisibility(R.id.iv_alarm, assignment.getAlarms() != 0 ? View.VISIBLE : View.GONE);

    Bundle extras = new Bundle();
    extras.putParcelable(Constants.EXTRA_MODEL, assignment);
    Intent fillInIntent = new Intent();
    fillInIntent.putExtras(extras);
    row.setOnClickFillInIntent(R.id.root, fillInIntent);

    return row;
}
 
Example 8
Source File: LessWidgetProvider.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
public static void setWidgetTheme(Context context, RemoteViews remoteViews) {

        int textColorId = AppPreference.getTextColor(context);
        int backgroundColorId = AppPreference.getWidgetBackgroundColor(context);
        int windowHeaderBackgroundColorId = AppPreference.getWindowHeaderBackgroundColorId(context);
        
        remoteViews.setInt(R.id.widget_less_3x1_widget_root, "setBackgroundColor", backgroundColorId);
        remoteViews.setTextColor(R.id.widget_less_3x1_widget_temperature, textColorId);
        remoteViews.setTextColor(R.id.widget_less_3x1_widget_second_temperature, textColorId);
        remoteViews.setTextColor(R.id.widget_less_3x1_widget_description, textColorId);
        remoteViews.setInt(R.id.widget_less_3x1_header_layout, "setBackgroundColor", windowHeaderBackgroundColorId);
    }
 
Example 9
Source File: CustomNotificationBuilder.java    From delion with Apache License 2.0 5 votes vote down vote up
private void configureSettingsButton(RemoteViews bigView) {
    if (mSettingsAction == null) {
        return;
    }
    bigView.setOnClickPendingIntent(R.id.origin, mSettingsAction.intent);
    if (useMaterial()) {
        bigView.setInt(R.id.origin_settings_icon, "setColorFilter", BUTTON_ICON_COLOR_MATERIAL);
    }
}
 
Example 10
Source File: CustomNotificationBuilder.java    From AndroidChromium with Apache License 2.0 5 votes vote down vote up
private void configureSettingsButton(RemoteViews bigView) {
    if (mSettingsAction == null) {
        return;
    }
    bigView.setOnClickPendingIntent(R.id.origin, mSettingsAction.intent);
    if (useMaterial()) {
        bigView.setInt(R.id.origin_settings_icon, "setColorFilter", BUTTON_ICON_COLOR_MATERIAL);
    }
}
 
Example 11
Source File: DownloadService.java    From fanfouapp-opensource with Apache License 2.0 5 votes vote down vote up
private void updateProgress(final int progress) {
    final RemoteViews view = new RemoteViews(getPackageName(),
            R.layout.download_notification);
    view.setTextViewText(R.id.download_notification_text, "正在下载饭否客户端 "
            + progress + "%");
    view.setInt(R.id.download_notification_progress, "setProgress",
            progress);
    this.notification.contentView = view;
    this.nm.notify(DownloadService.NOTIFICATION_PROGRESS_ID,
            this.notification);
}
 
Example 12
Source File: LocationWidgetProvider.java    From privatelocation with GNU General Public License v3.0 5 votes vote down vote up
public void setWidgetStop(Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    prefs.edit().putBoolean(context.getString(R.string.widget_prefs_service_id), false).apply();

    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    ComponentName thisWidget = new ComponentName(context, LocationWidgetProvider.class);
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.app_widget);

    remoteViews.setTextViewText(R.id.tvWidgetToggle, context.getResources().getString(R.string.widget_start_text));
    remoteViews.setImageViewResource(R.id.ivWidgetLocation, R.drawable.ic_widget_location_off_white_24dp);
    remoteViews.setInt(R.id.llWidget, "setBackgroundResource", R.color.colorWidgetStop);

    appWidgetManager.updateAppWidget(thisWidget, remoteViews);
}
 
Example 13
Source File: WidgetV24.java    From prayer-times-android with Apache License 2.0 4 votes vote down vote up
static void update2x2(Context context, AppWidgetManager appWidgetManager, int widgetId) {
    Theme theme = WidgetUtils.getTheme(widgetId);
    Times times = WidgetUtils.getTimes(widgetId);
    if (times == null) {
        WidgetUtils.showNoCityWidget(context, appWidgetManager, widgetId);
        return;
    }

    WidgetUtils.Size size = WidgetUtils.getSize(context, appWidgetManager, widgetId, 130f / 160f);
    int w = size.width;
    int h = size.height;
    if (w <= 0 || h <= 0)
        return;
    float scale = w / 10.5f;

    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.widget_2x2);
    remoteViews.setInt(R.id.widget_layout, "setBackgroundResource", theme.background);
    remoteViews.setViewPadding(R.id.padder, w / 2, h / 2, w / 2, h / 2);
    LocalDate date = LocalDate.now();
    LocalDateTime[] daytimes = {times.getTime(date, Vakit.FAJR.ordinal()), times.getTime(date, Vakit.SUN.ordinal()), times.getTime(date, Vakit.DHUHR.ordinal()), times.getTime(date, Vakit.ASR.ordinal()), times.getTime(date, Vakit.MAGHRIB.ordinal()),
            times.getTime(date, Vakit.ISHAA.ordinal())};


    remoteViews.setOnClickPendingIntent(R.id.widget_layout, TimesFragment.getPendingIntent(times));


    remoteViews.setTextViewText(R.id.city, times.getName());
    remoteViews.setTextColor(R.id.city, theme.textcolor);
    int current = times.getCurrentTime();
    int next = current + 1;
    int indicator = current;
    if ("next".equals(Preferences.VAKIT_INDICATOR_TYPE.get()))
        indicator = indicator + 1;
    int[] idsText = {R.id.fajrText, R.id.sunText, R.id.zuhrText, R.id.asrText, R.id.maghribText, R.id.ishaaText};
    int[] ids = {R.id.fajr, R.id.sun, R.id.zuhr, R.id.asr, R.id.maghrib, R.id.ishaa};

    boolean rtl = Utils.isRTL(context);

    for (Vakit v : Vakit.values()) {
        int i = v.ordinal();
        remoteViews.setTextViewTextSize(idsText[i], TypedValue.COMPLEX_UNIT_PX, scale * 1f);
        remoteViews.setTextViewTextSize(ids[i], TypedValue.COMPLEX_UNIT_PX, scale * 1f);
        remoteViews.setTextColor(idsText[i], theme.textcolor);
        remoteViews.setTextColor(ids[i], theme.textcolor);

        String name = Vakit.getByIndex(i).getString();
        String time = LocaleUtils.formatTime(daytimes[i].toLocalTime());
        if (Preferences.CLOCK_12H.get()) {
            time = time.replace(" ", "<sup><small>") + "</small></sup>";
        }

        if (Preferences.SHOW_ALT_WIDGET_HIGHLIGHT.get()) {
            if (v.ordinal() == indicator) {
                name = "<b><i>" + name + "</i></b>";
                time = "<b><i>" + time + "</i></b>";
            }
            remoteViews.setInt(idsText[i], "setBackgroundColor", 0);
            remoteViews.setInt(ids[i], "setBackgroundColor", 0);
        } else {
            if (v.ordinal() == indicator) {
                remoteViews.setInt(idsText[i], "setBackgroundColor", theme.hovercolor);
                remoteViews.setInt(ids[i], "setBackgroundColor", theme.hovercolor);
            } else {
                remoteViews.setInt(idsText[i], "setBackgroundColor", 0);
                remoteViews.setInt(ids[i], "setBackgroundColor", 0);
            }
        }

        remoteViews.setTextViewText(idsText[i], Html.fromHtml(!rtl ? name : time));
        remoteViews.setTextViewText(ids[i], Html.fromHtml(!rtl ? time : name));

        remoteViews.setViewPadding(idsText[i], (int) ((Preferences.CLOCK_12H.get() ? 1.25 : 1.75) * scale), 0, (int) scale / 4, 0);
        remoteViews.setViewPadding(ids[i], 0, 0, (int) ((Preferences.CLOCK_12H.get() ? 1.25 : 1.75) * scale), 0);

    }

    remoteViews.setTextViewTextSize(R.id.city, TypedValue.COMPLEX_UNIT_PX, scale * 1.3f);
    remoteViews.setTextColor(R.id.countdown, theme.textcolor);
    remoteViews.setViewPadding(R.id.city, (int) scale / 2, 0, (int) scale / 2, (int) scale / 4);

    if (Preferences.COUNTDOWN_TYPE.get().equals(Preferences.COUNTDOWN_TYPE_SHOW_SECONDS))
        remoteViews
                .setChronometer(R.id.countdown, times.getTime(LocalDate.now(), next).toDateTime().getMillis() - (System.currentTimeMillis() - SystemClock.elapsedRealtime()), null, true);
    else {
        String txt = LocaleUtils.formatPeriod(LocalDateTime.now(), times.getTime(LocalDate.now(), next), false);
        remoteViews.setString(R.id.countdown, "setFormat", txt);
        remoteViews.setChronometer(R.id.countdown, 0, txt, false);
    }
    remoteViews.setTextViewTextSize(R.id.countdown, TypedValue.COMPLEX_UNIT_PX, scale * 1.3f);
    appWidgetManager.updateAppWidget(widgetId, remoteViews);
}
 
Example 14
Source File: TableWidgetProvider.java    From android with Apache License 2.0 4 votes vote down vote up
@Override
protected RemoteViews buildLayout(AppWidgetManager awm, Context context, int appWidgetId, PrayerContext prayerContext) {
    Intent intent = new Intent(Extension.ACTION_MAIN_SCREEN);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
    int backgroundColor = mWidgetPreferences.getBackgroundColor();

    RemoteViews rv = new RemoteViews(context.getPackageName(), getWidgetLayout());
    rv.setOnClickPendingIntent(R.id.widget_header, pendingIntent);
    rv.setInt(R.id.widget_header, "setBackgroundColor", backgroundColor);
    rv.setViewVisibility(R.id.progress_bar, View.VISIBLE);
    rv.setViewVisibility(R.id.btn_retry, View.GONE);

    if (prayerContext == null) {
        return rv;
    }

    Resources r = context.getResources();

    String[] prayerNames = r.getStringArray(R.array.prayer_names);

    boolean showImsak = isImsakEnabled(awm, context, appWidgetId);
    boolean showDhuha = isDhuhaEnabled(awm, context, appWidgetId);
    boolean showSyuruk = isSyurukEnabled(awm, context, appWidgetId);
    boolean showMasihi = mWidgetPreferences.isMasihiDateEnabled();
    boolean showHijri = mWidgetPreferences.isHijriDateEnabled();

    int highlight = backgroundColor | 0xFF000000;
    int normal = ContextCompat.getColor(context, android.R.color.white);

    List<Prayer> cdpt = prayerContext.getCurrentPrayerList();
    List<Integer> hdate = prayerContext.getHijriDate();
    Calendar imsak = Calendar.getInstance();
    imsak.setTime(cdpt.get(0).getDate());

    Prayer cp = prayerContext.getCurrentPrayer();
    Prayer np = prayerContext.getNextPrayer();

    int cpi = cp.getIndex();
    int npi = np.getIndex();

    int hd = hdate.get(Prayer.HIJRI_DATE);
    int hm = hdate.get(Prayer.HIJRI_MONTH);
    int hy = hdate.get(Prayer.HIJRI_YEAR);
    int md = imsak.get(Calendar.DATE);
    int mm = imsak.get(Calendar.MONTH);
    int my = imsak.get(Calendar.YEAR);

    rv.setTextViewText(R.id.tv_prayer_name, prayerNames[npi]);
    rv.setTextViewText(R.id.tv_prayer_time, getFormattedDate(context, np.getDate()));
    rv.setTextViewText(R.id.tv_location, prayerContext.getLocationName());
    rv.setTextViewText(R.id.tv_hijri_date, getHijriDate(awm, context, appWidgetId, hd, hm, hy));
    rv.setTextViewText(R.id.tv_masihi_date, getMasihiDate(awm, context, appWidgetId, md, mm, my));
    rv.setViewVisibility(R.id.tv_hijri_date, showHijri ? View.VISIBLE : View.GONE);
    rv.setViewVisibility(R.id.tv_masihi_date, showMasihi ? View.VISIBLE : View.GONE);
    rv.setViewVisibility(R.id.progress_bar, View.GONE);
    rv.setViewVisibility(R.id.prayerlist, View.VISIBLE);
    rv.setViewVisibility(PRAYER_ROW[Prayer.PRAYER_IMSAK], showImsak ? View.VISIBLE : View.GONE);
    rv.setViewVisibility(PRAYER_ROW[Prayer.PRAYER_DHUHA], showDhuha ? View.VISIBLE : View.GONE);
    rv.setViewVisibility(PRAYER_ROW[Prayer.PRAYER_SYURUK], showSyuruk ? View.VISIBLE : View.GONE);

    for (int i = 0; i < prayerNames.length; i++) {
        rv.setTextViewText(PRAYER_NAME[i], prayerNames[i]);
        rv.setTextViewText(PRAYER_TIME[i], getFormattedDate(context, cdpt.get(i).getDate()));

        if (i == cpi || (!showImsak && i == Prayer.PRAYER_ISYAK && cpi == Prayer.PRAYER_IMSAK) ||
                (!showDhuha && i == Prayer.PRAYER_SYURUK && cpi == Prayer.PRAYER_DHUHA) ||
                (!showSyuruk && i == Prayer.PRAYER_ZOHOR && cpi == Prayer.PRAYER_SYURUK)) {
            rv.setTextColor(PRAYER_NAME[i], highlight);
            rv.setTextColor(PRAYER_TIME[i], highlight);
        } else {
            rv.setTextColor(PRAYER_NAME[i], normal);
            rv.setTextColor(PRAYER_TIME[i], normal);
        }
    }

    return rv;
}
 
Example 15
Source File: xDripWidget.java    From xDrip-Experimental with GNU General Public License v3.0 4 votes vote down vote up
private static void displayCurrentInfo(AppWidgetManager appWidgetManager, int appWidgetId, Context context, RemoteViews views) {
    BgGraphBuilder bgGraphBuilder = new BgGraphBuilder(context);
    BgReading lastBgreading = BgReading.lastNoSenssor();

    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
    boolean showLines = settings.getBoolean("widget_range_lines", false);

    if (lastBgreading != null) {
        double estimate = 0;
        int height = appWidgetManager.getAppWidgetOptions(appWidgetId).getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT);
        int width = appWidgetManager.getAppWidgetOptions(appWidgetId).getInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH);
        views.setImageViewBitmap(R.id.widgetGraph, new BgSparklineBuilder(context)
                .setBgGraphBuilder(bgGraphBuilder)
                .setHeight(height).setWidth(width).showHighLine(showLines).showLowLine(showLines).build());

        if ((new Date().getTime()) - (60000 * 11) - lastBgreading.timestamp > 0) {
            estimate = lastBgreading.calculated_value;
            Log.d(TAG, "old value, estimate " + estimate);
            views.setTextViewText(R.id.widgetBg, bgGraphBuilder.unitized_string(estimate));
            views.setTextViewText(R.id.widgetArrow, "--");
            views.setInt(R.id.widgetBg, "setPaintFlags", Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        } else {
            estimate = lastBgreading.calculated_value;
            String stringEstimate = bgGraphBuilder.unitized_string(estimate);
            String slope_arrow = lastBgreading.slopeArrow();
            if (lastBgreading.hide_slope) {
                slope_arrow = "--";
            }
            Log.d(TAG, "newish value, estimate " + stringEstimate + slope_arrow);
            views.setTextViewText(R.id.widgetBg, stringEstimate);
            views.setTextViewText(R.id.widgetArrow, slope_arrow);
            views.setInt(R.id.widgetBg, "setPaintFlags", 0);
        }
        List<BgReading> bgReadingList =  BgReading.latest(2);
        if(bgReadingList != null && bgReadingList.size() == 2) {

            views.setTextViewText(R.id.widgetDelta, bgGraphBuilder.unitizedDeltaString(true, true));
        } else {
            views.setTextViewText(R.id.widgetDelta, "--");
        }
        int timeAgo =(int) Math.floor((new Date().getTime() - lastBgreading.timestamp)/(1000*60));
        if (timeAgo == 1) {
            views.setTextViewText(R.id.readingAge, timeAgo + " Minute ago");
        } else {
            views.setTextViewText(R.id.readingAge, timeAgo + " Minutes ago");
        }
        if (timeAgo > 15) {
            views.setTextColor(R.id.readingAge, Color.parseColor("#FFBB33"));
        } else {
            views.setTextColor(R.id.readingAge, Color.WHITE);
        }

        if(settings.getBoolean("extra_status_line", false) && settings.getBoolean("widget_status_line", false)) {
            views.setTextViewText(R.id.widgetStatusLine, Home.extraStatusLine(settings));
            views.setViewVisibility(R.id.widgetStatusLine, View.VISIBLE);
        } else {
            views.setTextViewText(R.id.widgetStatusLine, "");
            views.setViewVisibility(R.id.widgetStatusLine, View.GONE);
        }

        if (bgGraphBuilder.unitized(estimate) <= bgGraphBuilder.lowMark) {
            views.setTextColor(R.id.widgetBg, Color.parseColor("#C30909"));
            views.setTextColor(R.id.widgetDelta, Color.parseColor("#C30909"));
            views.setTextColor(R.id.widgetArrow, Color.parseColor("#C30909"));
        } else if (bgGraphBuilder.unitized(estimate) >= bgGraphBuilder.highMark) {
            views.setTextColor(R.id.widgetBg, Color.parseColor("#FFBB33"));
            views.setTextColor(R.id.widgetDelta, Color.parseColor("#FFBB33"));
            views.setTextColor(R.id.widgetArrow, Color.parseColor("#FFBB33"));
        } else {
            views.setTextColor(R.id.widgetBg, Color.WHITE);
            views.setTextColor(R.id.widgetDelta, Color.WHITE);
            views.setTextColor(R.id.widgetArrow, Color.WHITE);
        }
    }
}
 
Example 16
Source File: CustomNotificationBuilder.java    From delion with Apache License 2.0 4 votes vote down vote up
@Override
public Notification build() {
    // A note about RemoteViews and updating notifications. When a notification is passed to the
    // {@code NotificationManager} with the same tag and id as a previous notification, an
    // in-place update will be performed. In that case, the actions of all new
    // {@link RemoteViews} will be applied to the views of the old notification. This is safe
    // for actions that overwrite old values such as setting the text of a {@code TextView}, but
    // care must be taken for additive actions. Especially in the case of
    // {@link RemoteViews#addView} the result could be to append new views below stale ones. In
    // that case {@link RemoteViews#removeAllViews} must be called before adding new ones.
    RemoteViews compactView =
            new RemoteViews(mContext.getPackageName(), R.layout.web_notification);
    RemoteViews bigView =
            new RemoteViews(mContext.getPackageName(), R.layout.web_notification_big);

    float fontScale = mContext.getResources().getConfiguration().fontScale;
    bigView.setInt(R.id.body, "setMaxLines", calculateMaxBodyLines(fontScale));
    int scaledPadding =
            calculateScaledPadding(fontScale, mContext.getResources().getDisplayMetrics());
    String formattedTime = "";

    // Temporarily allowing disk access. TODO: Fix. See http://crbug.com/577185
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    StrictMode.allowThreadDiskWrites();
    try {
        long time = SystemClock.elapsedRealtime();
        formattedTime = DateFormat.getTimeFormat(mContext).format(new Date());
        RecordHistogram.recordTimesHistogram("Android.StrictMode.NotificationUIBuildTime",
                SystemClock.elapsedRealtime() - time, TimeUnit.MILLISECONDS);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }

    for (RemoteViews view : new RemoteViews[] {compactView, bigView}) {
        view.setTextViewText(R.id.time, formattedTime);
        view.setTextViewText(R.id.title, mTitle);
        view.setTextViewText(R.id.body, mBody);
        view.setTextViewText(R.id.origin, mOrigin);
        view.setImageViewBitmap(R.id.icon, mLargeIcon);
        view.setViewPadding(R.id.title, 0, scaledPadding, 0, 0);
        view.setViewPadding(R.id.body_container, 0, scaledPadding, 0, scaledPadding);
        addWorkProfileBadge(view);

        int smallIconId = useMaterial() ? R.id.small_icon_overlay : R.id.small_icon_footer;
        view.setViewVisibility(smallIconId, View.VISIBLE);
        if (mSmallIconBitmap != null) {
            view.setImageViewBitmap(smallIconId, mSmallIconBitmap);
        } else {
            view.setImageViewResource(smallIconId, mSmallIconId);
        }
    }
    addActionButtons(bigView);
    configureSettingsButton(bigView);

    // Note: this is not a NotificationCompat builder so be mindful of the
    // API level of methods you call on the builder.
    Notification.Builder builder = new Notification.Builder(mContext);
    builder.setTicker(mTickerText);
    builder.setContentIntent(mContentIntent);
    builder.setDeleteIntent(mDeleteIntent);
    builder.setDefaults(mDefaults);
    builder.setVibrate(mVibratePattern);
    builder.setWhen(mTimestamp);
    builder.setOnlyAlertOnce(!mRenotify);
    builder.setContent(compactView);

    // Some things are duplicated in the builder to ensure the notification shows correctly on
    // Wear devices and custom lock screens.
    builder.setContentTitle(mTitle);
    builder.setContentText(mBody);
    builder.setSubText(mOrigin);
    builder.setLargeIcon(mLargeIcon);
    setSmallIconOnBuilder(builder, mSmallIconId, mSmallIconBitmap);
    for (Action action : mActions) {
        addActionToBuilder(builder, action);
    }
    if (mSettingsAction != null) {
        addActionToBuilder(builder, mSettingsAction);
    }

    Notification notification = builder.build();
    notification.bigContentView = bigView;
    return notification;
}
 
Example 17
Source File: Notifications.java    From android-quickstart with Apache License 2.0 4 votes vote down vote up
/**
 * Triggers/updates a payment notification
 */
public static void triggerPaymentNotification(Context context, String selectedOption) {

  final Resources res = context.getResources();
  final String packageName = context.getPackageName();

  // Create a custom notification layout
  RemoteViews notificationLayout = new RemoteViews(packageName, R.layout.notification_top_up_account);

  // Creates the selectable options
  final List<String> options = new ArrayList<>(OPTION_PRICE_CENTS.keySet());
  for (String option : options) {

    // Adjust color based on selected option
    int optionColor = res.getColor(R.color.price_button_grey, context.getTheme());
    int optionBg = R.drawable.price_button_background;
    if (option.equals(selectedOption)) {
      optionColor = Color.WHITE;
      optionBg = R.drawable.price_button_background_selected;
    }

    int buttonId = res.getIdentifier(OPTION_BUTTONS.get(option), "id", packageName);
    notificationLayout.setTextColor(buttonId, optionColor);
    notificationLayout.setInt(buttonId, "setBackgroundResource", optionBg);

    // Create pendingIntent to respond to the click event
    Intent selectOptionIntent = new Intent(context, PaymentNotificationIntentService.class);
    selectOptionIntent.setAction(ACTION_SELECT_PREFIX + option);
    notificationLayout.setOnClickPendingIntent(buttonId, PendingIntent.getService(
        context, REQUEST_CODE_SELECT_OPTION, selectOptionIntent,
        PendingIntent.FLAG_UPDATE_CURRENT));
  }

  // Set Google Pay button action
  Intent payIntent = new Intent(context, PaymentTransparentActivity.class);
  payIntent.setAction(ACTION_PAY_GOOGLE_PAY);
  payIntent.putExtra(OPTION_PRICE_EXTRA, OPTION_PRICE_CENTS.get(selectedOption));
  notificationLayout.setOnClickPendingIntent(
      R.id.googlePayButton, pendingIntentForActivity(context, payIntent));

  // Create a notification and set the notification channel
  Notification notification = new NotificationCompat
      .Builder(context, NOTIFICATION_CHANNEL_ID)
      .setSmallIcon(R.mipmap.ic_launcher)
      .setContentTitle(context.getString(R.string.notification_title))
      .setContentText(context.getString(R.string.notification_text))
      .setCustomBigContentView(notificationLayout)
      .setPriority(NotificationCompat.PRIORITY_DEFAULT)
      .setAutoCancel(false)
      .setOnlyAlertOnce(true)
      .build();

  // Trigger or update the notification.
  NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, notification);
}
 
Example 18
Source File: CustomNotificationBuilder.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
@Override
public Notification build() {
    // A note about RemoteViews and updating notifications. When a notification is passed to the
    // {@code NotificationManager} with the same tag and id as a previous notification, an
    // in-place update will be performed. In that case, the actions of all new
    // {@link RemoteViews} will be applied to the views of the old notification. This is safe
    // for actions that overwrite old values such as setting the text of a {@code TextView}, but
    // care must be taken for additive actions. Especially in the case of
    // {@link RemoteViews#addView} the result could be to append new views below stale ones. In
    // that case {@link RemoteViews#removeAllViews} must be called before adding new ones.
    RemoteViews compactView =
            new RemoteViews(mContext.getPackageName(), R.layout.web_notification);
    RemoteViews bigView =
            new RemoteViews(mContext.getPackageName(), R.layout.web_notification_big);

    float fontScale = mContext.getResources().getConfiguration().fontScale;
    bigView.setInt(R.id.body, "setMaxLines", calculateMaxBodyLines(fontScale));
    int scaledPadding =
            calculateScaledPadding(fontScale, mContext.getResources().getDisplayMetrics());
    String formattedTime = "";

    // Temporarily allowing disk access. TODO: Fix. See http://crbug.com/577185
    StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
    StrictMode.allowThreadDiskWrites();
    try {
        long time = SystemClock.elapsedRealtime();
        formattedTime = DateFormat.getTimeFormat(mContext).format(new Date());
        RecordHistogram.recordTimesHistogram("Android.StrictMode.NotificationUIBuildTime",
                SystemClock.elapsedRealtime() - time, TimeUnit.MILLISECONDS);
    } finally {
        StrictMode.setThreadPolicy(oldPolicy);
    }

    for (RemoteViews view : new RemoteViews[] {compactView, bigView}) {
        view.setTextViewText(R.id.time, formattedTime);
        view.setTextViewText(R.id.title, mTitle);
        view.setTextViewText(R.id.body, mBody);
        view.setTextViewText(R.id.origin, mOrigin);
        view.setImageViewBitmap(R.id.icon, getNormalizedLargeIcon());
        view.setViewPadding(R.id.title, 0, scaledPadding, 0, 0);
        view.setViewPadding(R.id.body_container, 0, scaledPadding, 0, scaledPadding);
        addWorkProfileBadge(view);

        int smallIconId = useMaterial() ? R.id.small_icon_overlay : R.id.small_icon_footer;
        view.setViewVisibility(smallIconId, View.VISIBLE);
        if (mSmallIconBitmap != null) {
            view.setImageViewBitmap(smallIconId, mSmallIconBitmap);
        } else {
            view.setImageViewResource(smallIconId, mSmallIconId);
        }
    }
    addActionButtons(bigView);
    configureSettingsButton(bigView);

    // Note: this is not a NotificationCompat builder so be mindful of the
    // API level of methods you call on the builder.
    Notification.Builder builder = new Notification.Builder(mContext);
    builder.setTicker(mTickerText);
    builder.setContentIntent(mContentIntent);
    builder.setDeleteIntent(mDeleteIntent);
    builder.setDefaults(mDefaults);
    builder.setVibrate(mVibratePattern);
    builder.setWhen(mTimestamp);
    builder.setOnlyAlertOnce(!mRenotify);
    builder.setContent(compactView);

    // Some things are duplicated in the builder to ensure the notification shows correctly on
    // Wear devices and custom lock screens.
    builder.setContentTitle(mTitle);
    builder.setContentText(mBody);
    builder.setSubText(mOrigin);
    builder.setLargeIcon(getNormalizedLargeIcon());
    setSmallIconOnBuilder(builder, mSmallIconId, mSmallIconBitmap);
    for (Action action : mActions) {
        addActionToBuilder(builder, action);
    }
    if (mSettingsAction != null) {
        addActionToBuilder(builder, mSettingsAction);
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // Notification.Builder.setPublicVersion was added in Android L.
        builder.setPublicVersion(createPublicNotification(mContext));
    }

    Notification notification = builder.build();
    notification.bigContentView = bigView;
    return notification;
}
 
Example 19
Source File: DynamicViewUtils.java    From dynamic-utils with Apache License 2.0 3 votes vote down vote up
/**
 * Set the background color for the remote views.
 *
 * @param remoteViews The remote views to set the background color.
 * @param viewId The id of the view whose background color to be set.
 * @param color The color value to be set.
 *
 * @see RemoteViews#setInt(int, String, int)
 */
public static void setBackgroundColor(@Nullable RemoteViews remoteViews,
        @IdRes int viewId, @ColorInt int color) {
    if (remoteViews == null) {
        return;
    }

    remoteViews.setInt(viewId, "setBackgroundColor", color);
}
 
Example 20
Source File: DynamicViewUtils.java    From dynamic-utils with Apache License 2.0 3 votes vote down vote up
/**
 * Set the color filter for the remote views.
 *
 * @param remoteViews The remote views to set the color filter.
 * @param viewId The id of the view whose color filter to be set.
 * @param color The color value to be set.
 *
 * @see RemoteViews#setInt(int, String, int)
 */
public static void setColorFilter(@Nullable RemoteViews remoteViews,
        @IdRes int viewId, @ColorInt int color) {
    if (remoteViews == null) {
        return;
    }

    remoteViews.setInt(viewId, "setColorFilter", color);
}