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

The following examples show how to use android.widget.RemoteViews#addView() . 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: NoiseService.java    From chromadoze with GNU General Public License v3.0 6 votes vote down vote up
private RemoteViews addButtonToNotification(Notification n) {
    // Create a new RV with a Stop button.
    RemoteViews rv = new RemoteViews(
            getPackageName(), R.layout.notification_with_stop_button);
    PendingIntent pendingIntent = PendingIntent.getService(
            this,
            0,
            newStopIntent(this, R.string.stop_reason_notification),
            PendingIntent.FLAG_CANCEL_CURRENT);
    rv.setOnClickPendingIntent(R.id.stop_button, pendingIntent);

    // Pre-render the original RV, and copy some of the colors.
    RemoteViews oldRV = getContentView(this, n);
    final View inflated = oldRV.apply(this, new FrameLayout(this));
    final TextView titleText = findTextView(inflated, getString(R.string.app_name));
    final TextView defaultText = findTextView(inflated, getString(R.string.notification_text));
    rv.setInt(R.id.divider, "setBackgroundColor", defaultText.getTextColors().getDefaultColor());
    rv.setInt(R.id.stop_button_square, "setBackgroundColor", titleText.getTextColors().getDefaultColor());

    // Insert a copy of the original RV into the new one.
    rv.addView(R.id.notification_insert, oldRV.clone());
    
    return rv;
}
 
Example 2
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 3
Source File: TimelineActivitySyncService.java    From aptoide-client with GNU General Public License v2.0 4 votes vote down vote up
public void sync(Context context, String packageName) {

        try {
            Log.d("AptoideTimeline", "Starting timelineActivityService");
            SharedPreferences sPref = PreferenceManager.getDefaultSharedPreferences(Aptoide.getContext());
            if(sPref.contains("timelineTimestamp") && sPref.getBoolean("socialtimelinenotifications", true)) {

                TimelineActivityJson timelineActivityJson = TimelineCheckRequestSync.getRequest("owned_activity, related_activity");
                int total_likes = timelineActivityJson.getOwned_activity().getTotal_likes().intValue();
                int total_comments = timelineActivityJson.getRelated_activity().getTotal_comments().intValue() + timelineActivityJson.getOwned_activity().getTotal_comments().intValue();

                String notificationText;

                if (total_comments == 0) {
                    notificationText = AptoideUtils.StringUtils.getFormattedString(context, R.string.notification_timeline_new_likes, total_likes);
                } else if (total_likes == 0) {
                    notificationText = AptoideUtils.StringUtils.getFormattedString(context, R.string.notification_timeline_new_comments, total_comments);
                } else {
                    notificationText = AptoideUtils.StringUtils.getFormattedString(context, R.string.notification_timeline_activity, total_comments, total_likes);
                }


                Intent intent = new Intent(context, MainActivity.class);
                intent.putExtra("fromTimeline", true);

                intent.setClassName(packageName, MainActivity.class.getName());
                intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setAction(Intent.ACTION_VIEW);

                PendingIntent resultPendingIntent = PendingIntent.getActivity(Aptoide.getContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

                Notification notification = new NotificationCompat.Builder(context)
                        .setSmallIcon(R.drawable.ic_stat_aptoide_fb_notification)
                        .setContentIntent(resultPendingIntent)
                        .setOngoing(false)
                        .setAutoCancel(true)
                        .setContentTitle(notificationText)
                        .setContentText(context.getString(R.string.notification_social_timeline)).build();
                notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;
                ArrayList<String> avatarLinks = new ArrayList<String>();

                try {

                    if (timelineActivityJson.getOwned_activity().getFriends() != null)
                        setAvatares(avatarLinks, timelineActivityJson.getOwned_activity().getFriends());
                    if (timelineActivityJson.getRelated_activity().getFriends() != null)
                        setAvatares(avatarLinks, timelineActivityJson.getRelated_activity().getFriends());

                    if (Build.VERSION.SDK_INT >= 16) {
                        RemoteViews expandedView = new RemoteViews(context.getPackageName(), R.layout.push_notification_timeline_activity);
                        expandedView.setTextViewText(R.id.description, notificationText);
                        expandedView.removeAllViews(R.id.linearLayout2);

                        for (String avatar : avatarLinks) {
                            Bitmap loadedImage = ImageLoader.getInstance().loadImageSync(avatar);
                            RemoteViews imageView = new RemoteViews(context.getPackageName(), R.layout.timeline_friend_iv);
                            imageView.setImageViewBitmap(R.id.friend_avatar, loadedImage);
                            expandedView.addView(R.id.linearLayout2, imageView);
                        }

                        notification.bigContentView = expandedView;
                    }

                    if (!avatarLinks.isEmpty()) {
                        final NotificationManager managerNotification = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                        managerNotification.notify(86458, notification);
                    }

                } catch (NullPointerException ignored) {
                    ignored.printStackTrace();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
 
Example 4
Source File: TimelinePostsSyncService.java    From aptoide-client with GNU General Public License v2.0 4 votes vote down vote up
public void sync(Context context, String packageName) {
    try {
        Log.d("AptoideTimeline", "Starting timelinePostsService");
        SharedPreferences sPref = PreferenceManager.getDefaultSharedPreferences(Aptoide.getContext());
        if(sPref.contains("timelineTimestamp") && sPref.getBoolean("socialtimelinenotifications", true)) {


            TimelineActivityJson timelineActivityJson = TimelineCheckRequestSync.getRequest("new_installs");

            Intent intent = new Intent(context, MainActivity.class);
            intent.putExtra("fromTimeline", true);

            intent.setClassName(packageName, MainActivity.class.getName());
            intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setAction(Intent.ACTION_VIEW);

            PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);


            Notification notification = new NotificationCompat.Builder(context)
                    .setSmallIcon(R.drawable.ic_stat_aptoide_fb_notification)
                    .setContentIntent(resultPendingIntent)
                    .setOngoing(false)
                    .setAutoCancel(true)
                    .setContentTitle(context.getString(R.string.notification_timeline_posts))
                    .setContentText(context.getString(R.string.notification_social_timeline)).build();
            notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;
            ArrayList<String> avatarLinks = new ArrayList<String>();

            try {

                setAvatares(avatarLinks, timelineActivityJson.getNew_installs().getFriends());

                if (Build.VERSION.SDK_INT >= 16) {
                    RemoteViews expandedView = new RemoteViews(context.getPackageName(), R.layout.push_notification_timeline_activity);
                    expandedView.setTextViewText(R.id.description, context.getString(R.string.notification_timeline_posts));
                    expandedView.removeAllViews(R.id.linearLayout2);
                    for (String avatar : avatarLinks) {
                        Bitmap loadedImage = ImageLoader.getInstance().loadImageSync(avatar);
                        RemoteViews imageView = new RemoteViews(context.getPackageName(), R.layout.timeline_friend_iv);
                        imageView.setImageViewBitmap(R.id.friend_avatar, loadedImage);
                        expandedView.addView(R.id.linearLayout2, imageView);
                    }

                    notification.bigContentView = expandedView;
                }


                if (!avatarLinks.isEmpty()) {
                    final NotificationManager managerNotification = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
                    managerNotification.notify(86459, notification);
                }


            } catch (NullPointerException ignored) {
            }

        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}
 
Example 5
Source File: CustomNotificationBuilder.java    From delion 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 6
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 7
Source File: SoundService.java    From volume_control_android with MIT License 4 votes vote down vote up
private static RemoteViews buildVolumeSlider(Context context, VolumeControl control, int typeId, String typeName) {
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.notification_volume_slider);
    views.removeAllViews(R.id.volume_slider);

    int maxLevel = control.getMaxLevel(typeId);
    int minLevel = control.getMinLevel(typeId);

    int currentLevel = control.getLevel(typeId);

    int maxSliderLevel = Math.min(maxLevel, 8);

    float delta = maxLevel / (float) maxSliderLevel;

    for (int i = control.getMinLevel(typeId); i <= maxSliderLevel; i++) {

        int volumeLevel = (maxLevel * i) / maxSliderLevel;

        boolean isActive = volumeLevel <= currentLevel;
        RemoteViews sliderItemView = new RemoteViews(
                context.getPackageName(),
                isActive ? R.layout.notification_slider_active : R.layout.notification_slider_inactive
        );

        if (i == maxSliderLevel) {
            sliderItemView.setViewVisibility(R.id.deliver_item, View.GONE);
        }

        int requestId = VOLUME_ID_PREFIX + (volumeLevel + 1) * 100 + typeId;


        sliderItemView.setOnClickPendingIntent(
                R.id.notification_slider_item,
                PendingIntent.getService(
                        context,
                        requestId,
                        setVolumeIntent(context, typeId, volumeLevel),
                        PendingIntent.FLAG_UPDATE_CURRENT)
        );
        views.addView(R.id.volume_slider, sliderItemView);
    }


    views.setTextViewText(R.id.volume_title, capitalize(typeName) + " " + (currentLevel - minLevel) + "/" + (maxLevel - minLevel));


    views.setOnClickPendingIntent(
            R.id.volume_up,
            PendingIntent.getService(
                    context,
                    VOLUME_ID_PREFIX + 10 + typeId,
                    setVolumeByDeltaIntent(context, typeId, delta),
                    PendingIntent.FLAG_UPDATE_CURRENT)
    );

    views.setOnClickPendingIntent(
            R.id.volume_down,
            PendingIntent.getService(
                    context,
                    VOLUME_ID_PREFIX + 20 + typeId,
                    setVolumeByDeltaIntent(context, typeId, -delta),
                    PendingIntent.FLAG_UPDATE_CURRENT)
    );

    return views;
}
 
Example 8
Source File: SoundService.java    From volume_control_android with MIT License 4 votes vote down vote up
private static Notification buildForegroundNotification(
        Context context,
        SoundProfile[] profiles,
        VolumeControl control,
        List<Integer> volumeTypesToShow
) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, staticNotificationId);


    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.notification_view);
    if (profiles != null) {
        remoteViews.removeAllViews(R.id.notifications_user_profiles);
        for (SoundProfile profile : profiles) {
            RemoteViews profileViews = new RemoteViews(context.getPackageName(), R.layout.notification_profile_name);
            profileViews.setTextViewText(R.id.notification_profile_title, profile.name);
            Intent i = getIntentForProfile(context, profile);
            PendingIntent pendingIntent;

            int requestId = PROFILE_ID_PREFIX + profile.id;

            pendingIntent = PendingIntent.getService(context, requestId, i, 0);
            profileViews.setOnClickPendingIntent(R.id.notification_profile_title, pendingIntent);
            remoteViews.addView(R.id.notifications_user_profiles, profileViews);
        }
    }

    if (volumeTypesToShow != null) {
        remoteViews.removeAllViews(R.id.volume_sliders);

        for (AudioType notificationType : AudioType.getAudioTypes(true)) {
            if (volumeTypesToShow.contains(notificationType.audioStreamName)) {
                remoteViews.addView(R.id.volume_sliders, buildVolumeSlider(context, control, notificationType.audioStreamName, context.getString(notificationType.nameId)));
            }
        }

        remoteViews.setOnClickPendingIntent(R.id.remove_notification_action, PendingIntent.getService(context, 100, getStopIntent(context), 0));
    }
    builder
            .setContentTitle(context.getString(R.string.app_name))
            .setOngoing(true)
            .setContentText(context.getString(R.string.notification_widget))
            .setSmallIcon(R.drawable.notification_icon)
            .setTicker(context.getString(R.string.app_name))
            .setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0));


    if ((volumeTypesToShow != null && volumeTypesToShow.size() > 0) || (profiles != null && profiles.length > 0)) {
        builder.setContentText(context.getString(R.string.notification_widget_featured))
                .setCustomBigContentView(remoteViews);
    }

    return builder.build();
}
 
Example 9
Source File: ReceiverWidgetProvider.java    From PowerSwitch_Android with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    Log.d("Updating Receiver Widgets...");
    // Perform this loop procedure for each App Widget that belongs to this provider
    for (int i = 0; i < appWidgetIds.length; i++) {
        int appWidgetId = appWidgetIds[i];
        RemoteViews remoteViews = new RemoteViews(context.getResources()
                .getString(eu.power_switch.shared.R.string.PACKAGE_NAME), R.layout.widget_receiver);

        try {
            ReceiverWidget receiverWidget = DatabaseHandler.getReceiverWidget(appWidgetId);
            Room room = DatabaseHandler.getRoom(receiverWidget.getRoomId());
            if (room != null) {
                Receiver receiver = DatabaseHandler.getReceiver(receiverWidget.getReceiverId());

                if (receiver != null) {
                    Apartment apartment = DatabaseHandler.getApartment(room.getApartmentId());
                    // update UI
                    remoteViews.setTextViewText(R.id.textView_receiver_widget_name, apartment.getName() + ": " + room.getName() + ": " + receiver.getName());

                    LinkedList<Button> buttons = receiver.getButtons();

                    // remove all previous buttons
                    remoteViews.removeAllViews(R.id.linearlayout_receiver_widget);

                    // add buttons from database
                    int buttonOffset = 0;
                    for (Button button : buttons) {
                        // set button action
                        RemoteViews buttonView = new RemoteViews(context.getResources()
                                .getString(eu.power_switch.shared.R.string.PACKAGE_NAME), R.layout.widget_receiver_button_layout);
                        SpannableString s = new SpannableString(button.getName());
                        s.setSpan(new StyleSpan(Typeface.BOLD), 0, button.getName().length(), 0);
                        buttonView.setTextViewText(R.id.button_widget_universal, s);
                        if (SmartphonePreferencesHandler.getHighlightLastActivatedButton() &&
                                receiver.getLastActivatedButtonId().equals(button.getId())) {
                            buttonView.setTextColor(R.id.button_widget_universal,
                                    ContextCompat.getColor(context, R.color.color_light_blue_a700));
                        }

                        PendingIntent intent = WidgetIntentReceiver.buildReceiverWidgetActionPendingIntent(context, apartment, room,
                                receiver, button, appWidgetId * 15 + buttonOffset);
                        buttonView.setOnClickPendingIntent(R.id.button_widget_universal, intent);

                        remoteViews.addView(R.id.linearlayout_receiver_widget, buttonView);
                        buttonOffset++;
                    }
                    remoteViews.setViewVisibility(R.id.linearlayout_receiver_widget, View.VISIBLE);
                } else {
                    remoteViews.setTextViewText(R.id.textView_receiver_widget_name, context.getString(R.string.receiver_not_found));
                    remoteViews.removeAllViews(R.id.linearlayout_receiver_widget);
                    remoteViews.setViewVisibility(R.id.linearlayout_receiver_widget, View.GONE);
                }
            } else {
                remoteViews.setTextViewText(R.id.textView_receiver_widget_name, context.getString(R.string.room_not_found));
                remoteViews.removeAllViews(R.id.linearlayout_receiver_widget);
                remoteViews.setViewVisibility(R.id.linearlayout_receiver_widget, View.GONE);
            }
        } catch (Exception e) {
            Log.e(e);
            remoteViews.setTextViewText(R.id.textView_receiver_widget_name, context.getString(R.string.unknown_error));
            remoteViews.removeAllViews(R.id.linearlayout_receiver_widget);
            remoteViews.setViewVisibility(R.id.linearlayout_receiver_widget, View.GONE);
        }
        appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
    }
    super.onUpdate(context, appWidgetManager, appWidgetIds);
}
 
Example 10
Source File: ConfigureReceiverWidgetActivity.java    From PowerSwitch_Android with GNU General Public License v3.0 4 votes vote down vote up
private void saveCurrentConfiguration() {
    try {
        // First, get the App Widget ID from the Intent that launched the Activity:
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null && extras.containsKey(AppWidgetManager.EXTRA_APPWIDGET_ID)) {
            int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
            // Perform your App Widget configuration:
            Apartment selectedApartment = getSelectedApartment();
            Room selectedRoom = selectedApartment.getRoom(spinnerRoom.getSelectedItem().toString());
            Receiver selectedReceiver = selectedRoom.getReceiver(spinnerReceiver.getSelectedItem().toString());

            // save new widget data to database
            ReceiverWidget receiverWidget = new ReceiverWidget(appWidgetId,
                    selectedRoom.getId(), selectedReceiver.getId());
            DatabaseHandler.addReceiverWidget(receiverWidget);
            // When the configuration is complete, get an instance of
            // the AppWidgetManager by calling getInstance(Context):
            AppWidgetManager appWidgetManager = AppWidgetManager
                    .getInstance(ConfigureReceiverWidgetActivity.this);
            // Update the App Widget with a RemoteViews layout by
            // calling updateAppWidget(int, RemoteViews):
            RemoteViews remoteViews = new RemoteViews(
                    getString(eu.power_switch.shared.R.string.PACKAGE_NAME), R.layout.widget_receiver);

            LinkedList<Button> buttons = selectedReceiver.getButtons();

            remoteViews.setTextViewText(R.id.textView_receiver_widget_name,
                    selectedApartment.getName() + ": " + selectedRoom.getName() + ": " + selectedReceiver.getName());

            int buttonOffset = 0;
            for (Button button : buttons) {
                // set button action
                RemoteViews buttonView = new RemoteViews(
                        getString(eu.power_switch.shared.R.string.PACKAGE_NAME), R.layout.widget_receiver_button_layout);
                SpannableString s = new SpannableString(button.getName());
                s.setSpan(new StyleSpan(Typeface.BOLD), 0, button.getName().length(), 0);
                buttonView.setTextViewText(R.id.button_widget_universal, s);

                if (SmartphonePreferencesHandler.getHighlightLastActivatedButton() &&
                        selectedReceiver.getLastActivatedButtonId().equals(button.getId())) {
                    buttonView.setTextColor(R.id.button_widget_universal,
                            ContextCompat.getColor(getApplicationContext(), R.color.color_light_blue_a700));
                }

                PendingIntent pendingIntent = WidgetIntentReceiver.buildReceiverWidgetActionPendingIntent(getApplicationContext(), selectedApartment, selectedRoom,
                        selectedReceiver, button, appWidgetId * 15 + buttonOffset);

                buttonView.setOnClickPendingIntent(R.id.button_widget_universal, pendingIntent);

                remoteViews.addView(R.id.linearlayout_receiver_widget, buttonView);
                buttonOffset++;
            }

            appWidgetManager.updateAppWidget(appWidgetId, remoteViews);

            // Finally, create the return Intent, set it with the
            // Activity result, and finish the Activity:
            Intent resultValue = new Intent();
            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
            setResult(RESULT_OK, resultValue);
            finish();
        }
    } catch (Exception e) {
        StatusMessageHandler.showErrorMessage(this, e);
    }
}
 
Example 11
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);
    }
}