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

The following examples show how to use android.widget.RemoteViews#setImageViewResource() . 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: APWidget.java    From Android-Wifi-Hotspot-Manager-Class with Apache License 2.0 6 votes vote down vote up
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    // TODO: Implement this method
    lg("on update");
    lg("Status: " + state);
    for (int i = 0; i < appWidgetIds.length; i++) {
        int currentId = appWidgetIds[i];
        lg("id: " + currentId);
        Intent intent = new Intent(context, APWidget.class);
        intent.putExtra(STATE, true);
        PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget);
        rv.setImageViewResource(R.id.widgetButton1, toggleButton());
        //rv.setTextViewText(R.id.widgetButton1,gettext(state));
        //rv.setTextColor(R.id.widgetButton1,getColor(!state));
        //rv.setTextColor(R.id.widgetTextView1,getColor(state));
        //rv.setTextViewText(R.id.widgetTextView1,getStatus(state));
        rv.setOnClickPendingIntent(R.id.widgetButton1, pi);
        //Intent tetherSettings = new Intent();
        //tetherSettings.setClassName(context, "com.android.settings.TetherSettings");
        rv.setOnClickPendingIntent(R.id.widgetLinearLayout1, tphs(context));
        appWidgetManager.updateAppWidget(currentId, rv);
        lg("Updated");
    }
    super.onUpdate(context, appWidgetManager, appWidgetIds);
}
 
Example 2
Source File: QuickStartWidget.java    From Virtual-Hosts with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.quick_start_widget);

    if (action.equals(ACTION_QUICK_START_BUTTON)) {
        if (VhostsService.isRunning()) {
            VhostsService.stopVService(context);
            views.setImageViewResource(R.id.imageButton, R.drawable.quick_start_off);
        } else {
            VhostsService.startVService(context,1);
            views.setImageViewResource(R.id.imageButton, R.drawable.quick_start_on);
        }
    }
    AppWidgetManager appWidgetManager=AppWidgetManager.getInstance(context);
    appWidgetManager.updateAppWidget(new ComponentName(context,QuickStartWidget.class),views);
    super.onReceive(context, intent);
}
 
Example 3
Source File: ImageTransformation.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/** @hide */
@TestApi
@Override
public void apply(@NonNull ValueFinder finder, @NonNull RemoteViews parentTemplate,
        int childViewId) throws Exception {
    final String value = finder.findByAutofillId(mId);
    if (value == null) {
        Log.w(TAG, "No view for id " + mId);
        return;
    }
    final int size = mOptions.size();
    if (sDebug) {
        Log.d(TAG, size + " multiple options on id " + childViewId + " to compare against");
    }

    for (int i = 0; i < size; i++) {
        final Option option = mOptions.get(i);
        try {
            if (option.pattern.matcher(value).matches()) {
                Log.d(TAG, "Found match at " + i + ": " + option);
                parentTemplate.setImageViewResource(childViewId, option.resId);
                if (option.contentDescription != null) {
                    parentTemplate.setContentDescription(childViewId,
                            option.contentDescription);
                }
                return;
            }
        } catch (Exception e) {
            // Do not log full exception to avoid PII leaking
            Log.w(TAG, "Error matching regex #" + i + "(" + option.pattern + ") on id "
                    + option.resId + ": " + e.getClass());
            throw e;

        }
    }
    if (sDebug) Log.d(TAG, "No match for " + value);
}
 
Example 4
Source File: AppWidgetSmall.java    From Music-Player with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Initialize given widgets to default state, where we launch Music on
 * default click and hide actions if service not running.
 */
protected void defaultAppWidget(final Context context, final int[] appWidgetIds) {
    final RemoteViews appWidgetView = new RemoteViews(context.getPackageName(), R.layout.app_widget_small);

    appWidgetView.setViewVisibility(R.id.media_titles, View.INVISIBLE);
    appWidgetView.setImageViewResource(R.id.image, R.drawable.default_album_art);
    appWidgetView.setImageViewBitmap(R.id.button_next, ImageUtil.createBitmap(ImageUtil.getTintedVectorDrawable(context, R.drawable.ic_skip_next_white_24dp, MaterialValueHelper.getSecondaryTextColor(context, true))));
    appWidgetView.setImageViewBitmap(R.id.button_prev, ImageUtil.createBitmap(ImageUtil.getTintedVectorDrawable(context, R.drawable.ic_skip_previous_white_24dp, MaterialValueHelper.getSecondaryTextColor(context, true))));
    appWidgetView.setImageViewBitmap(R.id.button_toggle_play_pause, ImageUtil.createBitmap(ImageUtil.getTintedVectorDrawable(context, R.drawable.ic_play_arrow_white_24dp, MaterialValueHelper.getSecondaryTextColor(context, true))));

    linkButtons(context, appWidgetView);
    pushUpdate(context, appWidgetIds, appWidgetView);
}
 
Example 5
Source File: LocationShortcutWidget.java    From edslite with GNU General Public License v2.0 5 votes vote down vote up
public static void setWidgetLayout(Context context,AppWidgetManager appWidgetManager,int widgetId,Settings.LocationShortcutWidgetInfo prefs,boolean isContainerOpen)
{
	RemoteViews views = new RemoteViews(context.getPackageName(),R.layout.widget);		
	views.setTextViewText(R.id.widgetTitleTextView, prefs.widgetTitle);
	//TypedValue typedValue = new TypedValue();
	//context.getTheme().resolveAttribute(isContainerOpen ? R.attr.widgetUnlockedIcon : R.attr.widgetLockedIcon, typedValue, true);
	//views.setImageViewResource(R.id.widgetLockImageButton, typedValue.resourceId);
	views.setImageViewResource(R.id.widgetLockImageButton, isContainerOpen ? R.drawable.widget_unlocked : R.drawable.widget_locked);
	
	Intent intent = new Intent(context, FileManagerActivity.class);
	intent.setData(Uri.parse(prefs.locationUriString));				
       PendingIntent pendingIntent = PendingIntent.getActivity(context, widgetId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
       views.setOnClickPendingIntent(R.id.widgetLockImageButton, pendingIntent);
	appWidgetManager.updateAppWidget(widgetId, views);
}
 
Example 6
Source File: BottomBarManager.java    From custom-tabs-client with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a RemoteViews that will be shown as the bottom bar of the custom tab.
 * @param showPlayIcon If true, a play icon will be shown, otherwise show a pause icon.
 * @return The created RemoteViews instance.
 */
public static RemoteViews createRemoteViews(Context context, boolean showPlayIcon) {
    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.remote_view);

    int iconRes = showPlayIcon ? R.drawable.ic_play : R.drawable.ic_stop;
    remoteViews.setImageViewResource(R.id.play_pause, iconRes);
    return remoteViews;
}
 
Example 7
Source File: Utils.java    From your-local-weather with GNU General Public License v3.0 5 votes vote down vote up
public static void setForecastIcon(RemoteViews remoteViews,
                                  Context context,
                                  int viewIconId,
                                   Integer weatherId,
                                   String iconId,
                                   double maxTemp,
                                   double maxWind,
                                   int fontColorId) {
    if ("weather_icon_set_fontbased".equals(AppPreference.getIconSet(context))) {
        remoteViews.setImageViewBitmap(viewIconId,
                createWeatherIconWithColor(context, getStrIcon(context, iconId), fontColorId));
    } else {
        remoteViews.setImageViewResource(viewIconId, Utils.getWeatherResourceIcon(weatherId, maxTemp, maxWind));
    }
}
 
Example 8
Source File: ClementineMediaSessionNotification.java    From Android-Remote with GNU General Public License v3.0 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void registerSession() {
    Resources res = mContext.getResources();
    mNotificationHeight = (int) res
            .getDimension(android.R.dimen.notification_large_icon_height);
    mNotificationWidth = (int) res.getDimension(android.R.dimen.notification_large_icon_width);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel notificationChannel = new NotificationChannel(
                App.notificationChannel, "Default",
                NotificationManager.IMPORTANCE_LOW
        );

        mNotificationManager.createNotificationChannel(notificationChannel);

        mNotificationBuilder = new Notification.Builder(mContext, App.notificationChannel)
                .setSmallIcon(R.drawable.notification)
                .setOngoing(true);
    } else {
        mNotificationBuilder = new Notification.Builder(mContext)
                .setSmallIcon(R.drawable.notification)
                .setOngoing(true);

    }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mNotificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
    }

    mNotificationBuilder.setContentIntent(Utilities.getClementineRemotePendingIntent(mContext));

    mNotificationView = new RemoteViews(mContext.getPackageName(), R.layout.notification_small);
    if (mTurnColor) {
        mNotificationView.setInt(R.id.noti, "setBackgroundColor", Color.TRANSPARENT);
        mNotificationView.setImageViewResource(R.id.noti_play_pause, R.drawable.ic_media_play);
        mNotificationView.setImageViewResource(R.id.noti_next, R.drawable.ic_media_next);
    }
    mNotificationBuilder.setContent(mNotificationView);
}
 
Example 9
Source File: ServiceToggle.java    From fitnotifications with Apache License 2.0 5 votes vote down vote up
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {

    // Perform this loop procedure for each App Widget that belongs to this provider
    for (int appWidgetId : appWidgetIds) {
        // Get the layout for the App Widget and attach an on-click listener
        // to the button
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.service_toggle_widget);
        if (NLService.isEnabled()) {
            views.setImageViewResource(R.id.widgetToggleButton,R.drawable.ic_speaker_notes_white_48dp);
            views.setInt(R.id.widgetToggleButton, "setBackgroundResource", R.drawable.round_rectangle_green);
            views.setTextViewText(R.id.widgetToggleText, context.getString(R.string.widget_on_text));
            views.setTextColor(R.id.widgetToggleText, ContextCompat.getColor(context, R.color.green));
        } else {
            views.setImageViewResource(R.id.widgetToggleButton,R.drawable.ic_speaker_notes_off_white_48dp);
            views.setInt(R.id.widgetToggleButton, "setBackgroundResource", R.drawable.round_rectangle_red);
            views.setTextViewText(R.id.widgetToggleText, context.getString(R.string.widget_off_text));
            views.setTextColor(R.id.widgetToggleText, ContextCompat.getColor(context, R.color.red));
        }

        views.setOnClickPendingIntent(
                                R.id.widgetToggleButton,
                                getPendingSelfIntent(context, appWidgetId, TOGGLE_CLICKED));

        // Tell the AppWidgetManager to perform an update on the current app widget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}
 
Example 10
Source File: WideWidget.java    From Jockey with Apache License 2.0 5 votes vote down vote up
private static RemoteViews setArtwork(RemoteViews views, @Nullable Bitmap artwork) {
    if (artwork == null) {
        views.setImageViewResource(R.id.widget_wide_artwork, R.drawable.art_default_xl);
    } else {
        views.setImageViewBitmap(R.id.widget_wide_artwork, artwork);
    }

    return views;
}
 
Example 11
Source File: QueueWidgetService.java    From Rey-MusicPlayer with Apache License 2.0 5 votes vote down vote up
@Override
public RemoteViews getViewAt(int position) {
    RemoteViews remoteViews = new RemoteViews(mContext.getPackageName(), R.layout.queue_widget_listview_layout);
    if (position <= getCount()) {

        String songTitle = songs.get(position)._title;

        ImageSize imageSize = new ImageSize(75, 75);

        long songDurationInMillis = 0;
        try {
            songDurationInMillis = songs.get(position)._duration;
        } catch (Exception e) {
        }

        remoteViews.setTextViewText(R.id.listViewSubText, songTitle);
        remoteViews.setTextViewText(R.id.listViewRightSubText, MusicUtils.convertMillisToMinsSecs(songDurationInMillis));


        Bitmap bitmap = ImageLoader.getInstance().loadImageSync(String.valueOf(MusicUtils.getAlbumArtUri(mApp.getService().getSongList().get(position)._albumId)), imageSize);
        if (bitmap != null) {
            remoteViews.setImageViewBitmap(R.id.listViewLeftIcon, bitmap);
        } else {
            remoteViews.setImageViewResource(R.id.listViewLeftIcon, R.mipmap.ic_launcher);
        }

    }


  /* This intent latches itself onto the pendingIntentTemplate from
 * LargeWidgetProvider.java and adds the extra "INDEX" argument to it. */
    Intent fillInIntent = new Intent();
    fillInIntent.putExtra("INDEX", position);
    remoteViews.setOnClickFillInIntent(R.id.listViewParent, fillInIntent);

    return remoteViews;
}
 
Example 12
Source File: CustomNotificationBuilder.java    From AndroidChromium with Apache License 2.0 4 votes vote down vote up
/**
 * If there are actions, shows the button related views, and adds a button for each action.
 */
private void addActionButtons(RemoteViews bigView) {
    // Remove the existing buttons in case an existing notification is being updated.
    bigView.removeAllViews(R.id.buttons);

    // Always set the visibility of the views associated with the action buttons. The current
    // visibility state is not known as perhaps an existing notification is being updated.
    int visibility = mActions.isEmpty() ? View.GONE : View.VISIBLE;
    bigView.setViewVisibility(R.id.button_divider, visibility);
    bigView.setViewVisibility(R.id.buttons, visibility);

    Resources resources = mContext.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    for (Action action : mActions) {
        RemoteViews view =
                new RemoteViews(mContext.getPackageName(), R.layout.web_notification_button);

        // If there is an icon then set it and add some padding.
        if (action.iconBitmap != null || action.iconId != 0) {
            if (useMaterial()) {
                view.setInt(R.id.button_icon, "setColorFilter", BUTTON_ICON_COLOR_MATERIAL);
            }

            int iconWidth = 0;
            if (action.iconBitmap != null) {
                view.setImageViewBitmap(R.id.button_icon, action.iconBitmap);
                iconWidth = action.iconBitmap.getWidth();
            } else if (action.iconId != 0) {
                view.setImageViewResource(R.id.button_icon, action.iconId);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeResource(resources, action.iconId, options);
                iconWidth = options.outWidth;
            }
            iconWidth = dpToPx(
                    Math.min(pxToDp(iconWidth, metrics), MAX_ACTION_ICON_WIDTH_DP), metrics);

            // Set the padding of the button so the text does not overlap with the icon. Flip
            // between left and right manually as RemoteViews does not expose a method that sets
            // padding in a writing-direction independent way.
            int buttonPadding =
                    dpToPx(BUTTON_PADDING_START_DP + BUTTON_ICON_PADDING_DP, metrics)
                    + iconWidth;
            int buttonPaddingLeft = LocalizationUtils.isLayoutRtl() ? 0 : buttonPadding;
            int buttonPaddingRight = LocalizationUtils.isLayoutRtl() ? buttonPadding : 0;
            view.setViewPadding(R.id.button, buttonPaddingLeft, 0, buttonPaddingRight, 0);
        }

        view.setTextViewText(R.id.button, action.title);
        view.setOnClickPendingIntent(R.id.button, action.intent);
        bigView.addView(R.id.buttons, view);
    }
}
 
Example 13
Source File: ClementineWidgetProvider.java    From Android-Remote with GNU General Public License v3.0 4 votes vote down vote up
private void updateViewsOnConnectionStatusChange(Context context, RemoteViews views) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean canConnect = prefs.contains(SharedPreferencesKeys.SP_KEY_IP);

    views.setBoolean(R.id.widget_btn_play_pause, "setEnabled", false);
    views.setBoolean(R.id.widget_btn_next, "setEnabled", false);

    switch (mCurrentConnectionStatus) {
        case IDLE:
        case DISCONNECTED:
            // Reset play button
            views.setImageViewResource(R.id.widget_btn_play_pause,
                    R.drawable.ab_media_play);

            if (canConnect) {
                // Textviews
                views.setTextViewText(R.id.widget_subtitle, prefs.getString(
                        SharedPreferencesKeys.SP_KEY_IP, ""));
                views.setTextViewText(R.id.widget_title,
                        context.getString(R.string.widget_connect_to));

                // Start an intent to connect to Clemetine
                Intent intentConnect = new Intent(context, ClementineBroadcastReceiver.class);
                intentConnect.setAction(ClementineBroadcastReceiver.CONNECT);
                views.setOnClickPendingIntent(R.id.widget_layout, PendingIntent
                        .getBroadcast(context, 0, intentConnect, PendingIntent.FLAG_ONE_SHOT));
            } else {
                // Textviews
                views.setTextViewText(R.id.widget_subtitle,
                        context.getString(R.string.widget_open_clementine));
                views.setTextViewText(R.id.widget_title,
                        context.getString(R.string.widget_not_connected));

                // Start Clementine Remote
                views.setOnClickPendingIntent(R.id.widget_layout,
                        Utilities.getClementineRemotePendingIntent(context));
            }
            break;
        case CONNECTING:
            views.setTextViewText(R.id.widget_subtitle, "");
            views.setTextViewText(R.id.widget_title,
                    context.getString(R.string.connectdialog_connecting));
            break;
        case NO_CONNECTION:
            views.setTextViewText(R.id.widget_subtitle,
                    context.getString(R.string.widget_open_clementine));
            views.setTextViewText(R.id.widget_title,
                    context.getString(R.string.widget_couldnt_connect));
            // Start Clementine Remote
            views.setOnClickPendingIntent(R.id.widget_layout,
                    Utilities.getClementineRemotePendingIntent(context));
            break;
        case CONNECTED:
            views.setBoolean(R.id.widget_btn_play_pause, "setEnabled", true);
            views.setBoolean(R.id.widget_btn_next, "setEnabled", true);
            break;
    }
}
 
Example 14
Source File: GameWallpaperService.java    From homescreenarcade with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getBooleanExtra(ArcadeCommon.STATUS_RESET_SCORE, false)) {
        score = 0;
    } else {
        score += intent.getIntExtra(ArcadeCommon.STATUS_INCREMENT_SCORE, 0);
    }

    RemoteViews notifViews = new RemoteViews(context.getPackageName(),
            R.layout.status_notification);
    notifViews.setTextViewText(R.id.title, getString(titleResID));
    notifViews.setImageViewResource(R.id.notif_icon, notifIconResID);

    NotificationManager notifMgr =
            (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
    notifViews.setTextViewText(R.id.score, getString(R.string.score, score));

    int newLevel = intent.getIntExtra(ArcadeCommon.STATUS_LEVEL, level);
    if (newLevel != level) {
        setLevel(newLevel);
    }
    if (level >= 0) {
        notifViews.setTextViewText(R.id.level, getString(R.string.level, level));
    }

    setLives(intent.getIntExtra(ArcadeCommon.STATUS_LIVES, lives));
    if (previewActive) {
        return;
    }
    
    notifViews.removeAllViews(R.id.lives_area);
    if (lives < 0) {
        // Game over, man
        RemoteViews gameOver = new RemoteViews(getPackageName(), R.layout.status_text);
        gameOver.setTextViewText(R.id.status_text, "Game Over");
        notifViews.addView(R.id.lives_area, gameOver);
        if (!isPaused) {
            onPause();
        }
    } else {
        Bitmap lifeBitmap = BitmapFactory.decodeResource(getResources(), lifeIconResId);
        for (int i = 0; i < lives; i++) {
            RemoteViews thisLife = new RemoteViews(getPackageName(), R.layout.status_life_icon);
            thisLife.setBitmap(R.id.life_icon, "setImageBitmap", lifeBitmap);
            notifViews.addView(R.id.lives_area, thisLife);
        }
    }

    Bitmap pauseBtn = BitmapFactory.decodeResource(getResources(),
            isPaused || (readyTime > 0) 
                    ? R.drawable.ic_play_circle_outline_white_48dp
                    : R.drawable.ic_pause_circle_outline_white_48dp);
    notifViews.setBitmap(R.id.play_pause, "setImageBitmap", pauseBtn);
    notifViews.setOnClickPendingIntent(R.id.play_pause,
            PendingIntent.getBroadcast(context, 0, 
                    new Intent(ArcadeCommon.ACTION_PAUSE), 0));
    
    final NotificationCompat.Builder notif = new NotificationCompat.Builder(context)
            .setSmallIcon(notifIconResID)
            .setContent(notifViews)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setVisibility(VISIBILITY_SECRET); // keep the scroreboard off the lock screen
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        // This forces a heads-up notification
        notif.setVibrate(new long[0]);
    }

    notifMgr.notify(0, notif.build());
}
 
Example 15
Source File: ClockDayVerticalWidgetIMP.java    From GeometricWeather with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static RemoteViews getRemoteViews(Context context, Location location,
                                         String viewStyle, String cardStyle, int cardAlpha,
                                         String textColor, int textSize,
                                         boolean hideSubtitle, String subtitleData, String clockFont) {
    boolean dayTime = TimeManager.isDaylight(location);

    SettingsOptionManager settings = SettingsOptionManager.getInstance(context);
    TemperatureUnit temperatureUnit = settings.getTemperatureUnit();
    boolean minimalIcon = settings.isWidgetMinimalIconEnabled();
    boolean touchToRefresh = settings.isWidgetClickToRefreshEnabled();

    WidgetColor color = new WidgetColor(context, dayTime, cardStyle, textColor);

    int textColorInt;
    if (color.darkText) {
        textColorInt = ContextCompat.getColor(context, R.color.colorTextDark);
    } else {
        textColorInt = ContextCompat.getColor(context, R.color.colorTextLight);
    }

    RemoteViews views = buildWidgetViewDayPart(
            context, location,
            temperatureUnit,
            dayTime, textColorInt, textSize,
            minimalIcon, color.darkText,
            clockFont, viewStyle,
            hideSubtitle, subtitleData
    );

    if (color.showCard) {
        views.setImageViewResource(
                R.id.widget_clock_day_card,
                getCardBackgroundId(context, color.darkCard, cardAlpha)
        );
        views.setViewVisibility(R.id.widget_clock_day_card, View.VISIBLE);
    } else {
        views.setViewVisibility(R.id.widget_clock_day_card, View.GONE);
    }

    setOnClickPendingIntent(context, views, location, subtitleData, touchToRefresh);

    return views;
}
 
Example 16
Source File: DayWidgetIMP.java    From GeometricWeather with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static RemoteViews getRemoteViews(Context context,
                                         Location location,
                                         String viewStyle, String cardStyle, int cardAlpha,
                                         String textColor, int textSize,
                                         boolean hideSubtitle, String subtitleData) {

    boolean dayTime = TimeManager.isDaylight(location);

    SettingsOptionManager settings = SettingsOptionManager.getInstance(context);
    TemperatureUnit temperatureUnit = settings.getTemperatureUnit();
    boolean minimalIcon = settings.isWidgetMinimalIconEnabled();
    boolean touchToRefresh = settings.isWidgetClickToRefreshEnabled();

    WidgetColor color = new WidgetColor(context, dayTime, cardStyle, textColor);
    if (viewStyle.equals("pixel") || viewStyle.equals("nano")
            || viewStyle.equals("oreo") || viewStyle.equals("oreo_google_sans")
            || viewStyle.equals("temp")) {
        color.showCard = false;
        color.darkText = textColor.equals("dark")
                || (textColor.equals("auto") && isLightWallpaper(context));
    }

    RemoteViews views = buildWidgetView(
            context, location, temperatureUnit,
            dayTime, minimalIcon,
            viewStyle, color, textSize,
            hideSubtitle, subtitleData);
    Weather weather = location.getWeather();
    if (weather == null) {
        return views;
    }

    if (color.showCard) {
        views.setImageViewResource(
                R.id.widget_day_card,
                getCardBackgroundId(context, color.darkCard, cardAlpha)
        );
        views.setViewVisibility(R.id.widget_day_card, View.VISIBLE);
    } else {
        views.setViewVisibility(R.id.widget_day_card, View.GONE);
    }

    setOnClickPendingIntent(context, views, location, viewStyle, subtitleData, touchToRefresh);

    return views;
}
 
Example 17
Source File: CustomNotificationBuilder.java    From 365browser with Apache License 2.0 4 votes vote down vote up
/**
 * If there are actions, shows the button related views, and adds a button for each action.
 */
private void addActionButtons(RemoteViews bigView) {
    // Remove the existing buttons in case an existing notification is being updated.
    bigView.removeAllViews(R.id.buttons);

    // Always set the visibility of the views associated with the action buttons. The current
    // visibility state is not known as perhaps an existing notification is being updated.
    int visibility = mActions.isEmpty() ? View.GONE : View.VISIBLE;
    bigView.setViewVisibility(R.id.button_divider, visibility);
    bigView.setViewVisibility(R.id.buttons, visibility);

    Resources resources = mContext.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    for (Action action : mActions) {
        RemoteViews view =
                new RemoteViews(mContext.getPackageName(), R.layout.web_notification_button);

        // If there is an icon then set it and add some padding.
        if (action.iconBitmap != null || action.iconId != 0) {
            if (useMaterial()) {
                view.setInt(R.id.button_icon, "setColorFilter", BUTTON_ICON_COLOR_MATERIAL);
            }

            int iconWidth = 0;
            if (action.iconBitmap != null) {
                view.setImageViewBitmap(R.id.button_icon, action.iconBitmap);
                iconWidth = action.iconBitmap.getWidth();
            } else if (action.iconId != 0) {
                view.setImageViewResource(R.id.button_icon, action.iconId);
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeResource(resources, action.iconId, options);
                iconWidth = options.outWidth;
            }
            iconWidth = dpToPx(
                    Math.min(pxToDp(iconWidth, metrics), MAX_ACTION_ICON_WIDTH_DP), metrics);

            // Set the padding of the button so the text does not overlap with the icon. Flip
            // between left and right manually as RemoteViews does not expose a method that sets
            // padding in a writing-direction independent way.
            int buttonPadding =
                    dpToPx(BUTTON_PADDING_START_DP + BUTTON_ICON_PADDING_DP, metrics)
                    + iconWidth;
            int buttonPaddingLeft = LocalizationUtils.isLayoutRtl() ? 0 : buttonPadding;
            int buttonPaddingRight = LocalizationUtils.isLayoutRtl() ? buttonPadding : 0;
            view.setViewPadding(R.id.button, buttonPaddingLeft, 0, buttonPaddingRight, 0);
        }

        view.setTextViewText(R.id.button, action.title);
        view.setOnClickPendingIntent(R.id.button, action.intent);
        bigView.addView(R.id.buttons, view);
    }
}
 
Example 18
Source File: DownloadService.java    From android-project-wo2b with Apache License 2.0 4 votes vote down vote up
/**
 * 开始下载
 * 
 * @param context
 * @param title
 * @param icon
 */
private void notifyDownloadStart(Context context, Request request)
{
	RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.api_download_notification);
	remoteViews.setProgressBar(R.id.noti_progressBar, PROGRESSBAR_MAX, 0, false);
	remoteViews.setImageViewResource(R.id.noti_icon, R.drawable.notification_remote_icon);
	remoteViews.setTextViewText(R.id.noti_file_name, request.mTitle);
	
	String host = CommonUtils.getHost(request.mDownloadUrl);
	if (CommonUtils.isWo2bHost(request.mDownloadUrl))
	{
		remoteViews.setTextViewText(R.id.noti_progressBarLeft, "www.wo2b.com");
	}
	else
	{
		remoteViews.setTextViewText(R.id.noti_progressBarLeft, host);
	}
	
	
	// 执行取消操作的PendingIntent, 向DownloadService发起取消下载的命令
	Intent cancelIntent = new Intent();
	cancelIntent.setClass(context, DownloadService.class);
	cancelIntent.putExtra(DownloadService.EXTRA_EVENT_TYPE, DownloadService.EVENT_CANCEL);
	cancelIntent.putExtra(DownloadService.EXTRA_DOWNLOAD_URL, request.mDownloadUrl);

	PendingIntent cancelPendingIntent = PendingIntent.getService(context, 100, cancelIntent,
			PendingIntent.FLAG_CANCEL_CURRENT);
	remoteViews.setOnClickPendingIntent(R.id.noti_cancel, cancelPendingIntent);
	
	// 消息信息设置
	Notification notification = new Notification();
	notification.tickerText = request.mTitle;
	notification.icon = R.drawable.notification_icon;
	notification.contentView = remoteViews;
	// notification.flags = Notification.FLAG_AUTO_CANCEL;
	notification.flags = Notification.FLAG_ONGOING_EVENT;

	// 点击通知栏
	Intent intent = new Intent();
	intent.setAction("com.wo2b.download.AActivity");
	// intent.setClass(context, Download.class);

	notification.contentIntent = PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_CANCEL_CURRENT);
	
	// 生成通知ID
	int notificationId = new Random().nextInt(10000);

	mNotificationManager.notify(notificationId, notification);
	
	request.mNotification = notification;
	request.mNotificationId = notificationId;

}
 
Example 19
Source File: QueueWidgetProvider.java    From Rey-MusicPlayer with Apache License 2.0 4 votes vote down vote up
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    final int N = appWidgetIds.length;


    for (int i = 0; i < N; i++) {
        int currentAppWidgetId = appWidgetIds[i];
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.queue_widget_layout);


        if (mApp.isServiceRunning()) {
            Bitmap art = mApp.getService().getSongDataHelper().getAlbumArt();
            if (art != null) {
                views.setImageViewBitmap(R.id.widget_album_art, mApp.getService().getSongDataHelper().getAlbumArt());
            } else {
                views.setImageViewResource(R.id.widget_album_art, R.mipmap.ic_launcher);
            }

            String songTitle = mApp.getService().getSongDataHelper().getTitle();
            views.setTextViewText(R.id.songName5, songTitle);

            String songArtistName = mApp.getService().getSongDataHelper().getArtist();
            views.setTextViewText(R.id.artistName, songArtistName);

            Intent playPauseIntent = new Intent();
            playPauseIntent.setAction(Constants.ACTION_PAUSE);
            playPauseIntent.putExtra("isfromSmallWidget", true);
            PendingIntent playpausePendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, playPauseIntent, 0);
            views.setOnClickPendingIntent(R.id.notification_expanded_base_play, playpausePendingIntent);


            Intent previousIntent = new Intent();
            previousIntent.setAction(Constants.ACTION_PREVIOUS);
            PendingIntent previousPendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, previousIntent, 0);
            views.setOnClickPendingIntent(R.id.notification_expanded_base_previous, previousPendingIntent);

            Intent nextIntent = new Intent();
            nextIntent.setAction(Constants.ACTION_NEXT);
            PendingIntent nextPendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, nextIntent, 0);
            views.setOnClickPendingIntent(R.id.notification_expanded_base_next, nextPendingIntent);


            Intent nowPlayingIntent = new Intent(context, MainActivity.class);
            nowPlayingIntent.putExtra(Constants.FROM_NOTIFICATION, true);
            PendingIntent configPendingIntent = PendingIntent.getActivity(context, 0, nowPlayingIntent, 0);
            views.setOnClickPendingIntent(R.id.widget_album_art, configPendingIntent);


            if (mApp.isServiceRunning()) {
                if (mApp.getService().getMediaPlayer().isPlaying()) {
                    views.setImageViewResource(R.id.notification_expanded_base_play, R.drawable.btn_playback_pause_light);
                } else {
                    views.setImageViewResource(R.id.notification_expanded_base_play, R.drawable.btn_playback_play_light);
                }
            } else {
                views.setImageViewResource(R.id.notification_expanded_base_play, R.drawable.btn_playback_play_light);
            }

        /* Create a pendingIntent that will serve as a general template for the clickListener.
         * We'll create a fillInIntent in LargeWidgetAdapterService.java that will provide the
         * index of the listview item that's been clicked. */

            Intent intent = new Intent();
            intent.setAction("com.reyansh.audio.audioplayer.free.action.STOP");
            PendingIntent pendingIntentTemplate = PendingIntent.getBroadcast(mApp.getApplicationContext(), 0, intent, 0);
            views.setPendingIntentTemplate(R.id.listview, pendingIntentTemplate);


            //Create the intent to fire up the service that will back the adapter of the listview.
            Intent serviceIntent = new Intent(mApp.getApplicationContext(), QueueWidgetService.class);
            serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetIds[i]);
            serviceIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME)));
            Common.getInstance().sendBroadcast(serviceIntent);

            views.setRemoteAdapter(R.id.listview, serviceIntent);

            appWidgetManager.notifyAppWidgetViewDataChanged(mAppWidgetIds, R.id.recyclerView);

            try {
                appWidgetManager.updateAppWidget(currentAppWidgetId, views);
            } catch (Exception e) {
                continue;
            }
        }

    }
}
 
Example 20
Source File: DSubWidgetProvider.java    From Popeens-DSub with GNU General Public License v3.0 4 votes vote down vote up
/**
    * Update all active widget instances by pushing changes
    */
   private void performUpdate(Context context, DownloadService service, int[] appWidgetIds, boolean playing) {
       final Resources res = context.getResources();
       final RemoteViews views = new RemoteViews(context.getPackageName(), getLayout());

	if(playing) {
		views.setViewVisibility(R.id.widget_root, View.VISIBLE);
	} else {
		// Hide widget
		SharedPreferences prefs = Util.getPreferences(context);
		if(prefs.getBoolean(Constants.PREFERENCES_KEY_HIDE_WIDGET, false)) {
			views.setViewVisibility(R.id.widget_root, View.GONE);
		}
	}

// Get Entry from current playing DownloadFile
       MusicDirectory.Entry currentPlaying = null;
       if(service == null) {
       	// Deserialize from playling list to setup
           try {
               PlayerQueue state = FileUtil.deserialize(context, DownloadServiceLifecycleSupport.FILENAME_DOWNLOADS_SER, PlayerQueue.class);
               if (state != null && state.currentPlayingIndex != -1) {
                   currentPlaying = state.songs.get(state.currentPlayingIndex);
               }
           } catch(Exception e) {
               Log.e(TAG, "Failed to grab current playing", e);
           }
       } else {
		currentPlaying = service.getCurrentPlaying() == null ? null : service.getCurrentPlaying().getSong();
       }
       
       String title = currentPlaying == null ? null : currentPlaying.getTitle();
       CharSequence artist = currentPlaying == null ? null : currentPlaying.getArtist();
	CharSequence album = currentPlaying == null ? null : currentPlaying.getAlbum();
       CharSequence errorState = null;

       // Show error message?
       String status = Environment.getExternalStorageState();
       if (status.equals(Environment.MEDIA_SHARED) ||
           status.equals(Environment.MEDIA_UNMOUNTED)) {
           errorState = res.getText(R.string.widget_sdcard_busy);
       } else if (status.equals(Environment.MEDIA_REMOVED)) {
           errorState = res.getText(R.string.widget_sdcard_missing);
       } else if (currentPlaying == null) {
           errorState = res.getText(R.string.widget_initial_text);
       }

       setText(views, title, artist, album, errorState);

       // Set correct drawable for pause state
       if (playing) {
           views.setImageViewResource(R.id.control_play, R.drawable.media_pause_dark);
       } else {
           views.setImageViewResource(R.id.control_play, R.drawable.media_start_dark);
       }

       setImage(views, context, currentPlaying);

       // Link actions buttons to intents
       linkButtons(context, views, currentPlaying != null);

       pushUpdate(context, appWidgetIds, views);
   }