Example usage for android.widget RemoteViews RemoteViews

List of usage examples for android.widget RemoteViews RemoteViews

Introduction

In this page you can find the example usage for android.widget RemoteViews RemoteViews.

Prototype

public RemoteViews(RemoteViews landscape, RemoteViews portrait) 

Source Link

Document

Create a new RemoteViews object that will inflate as the specified landspace or portrait RemoteViews, depending on the current configuration.

Usage

From source file:eu.power_switch.widget.provider.ReceiverWidgetProvider.java

@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 {/*from   ww  w  .j ava 2  s . c  o  m*/
            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);
}

From source file:com.oryx.notifications.NotificationService.java

private RemoteViews getNotiView(PendingIntent pi, PendingIntent pi2) {
    RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.noti_custom);
    remoteViews.setTextViewText(R.id.notiURL, this.url);
    remoteViews.setOnClickPendingIntent(R.id.notipause, pi);
    remoteViews.setOnClickPendingIntent(R.id.notiplay, pi2);
    return remoteViews;
}

From source file:com.audiokernel.euphonyrmt.service.NotificationHandler.java

NotificationHandler(final MPDroidService serviceContext) {
    super();/*from  w  w w. j a v a 2s  .co  m*/

    mServiceContext = serviceContext;

    mNotificationManager = (NotificationManager) mServiceContext.getSystemService(Context.NOTIFICATION_SERVICE);

    final RemoteViews resultView = new RemoteViews(mServiceContext.getPackageName(), R.layout.notification);

    buildBaseNotification(resultView);
    mNotification = buildCollapsedNotification(serviceContext).setContent(resultView).build();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        buildExpandedNotification();
    }

    mCurrentTrack = new Music();
    mIsActive = true;
}

From source file:com.example.android.customnotifications.MainActivity.java

/**
 * This sample demonstrates notifications with custom content views.
 *
 * <p>On API level 16 and above a big content view is also defined that is used for the
 * 'expanded' notification. The notification is created by the NotificationCompat.Builder.
 * The expanded content view is set directly on the {@link android.app.Notification} once it has been build.
 * (See {@link android.app.Notification#bigContentView}.) </p>
 *
 * <p>The content views are inflated as {@link android.widget.RemoteViews} directly from their XML layout
 * definitions using {@link android.widget.RemoteViews#RemoteViews(String, int)}.</p>
 *///from  w w  w.j  ava2  s .c o m
private void createNotification() {
    // BEGIN_INCLUDE(notificationCompat)
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    // END_INCLUDE(notificationCompat)

    // BEGIN_INCLUDE(intent)
    //Create Intent to launch this Activity again if the notification is clicked.
    Intent i = new Intent(this, MainActivity.class);
    i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(intent);
    // END_INCLUDE(intent)

    // BEGIN_INCLUDE(ticker)
    // Sets the ticker text
    builder.setTicker(getResources().getString(R.string.custom_notification));

    // Sets the small icon for the ticker
    builder.setSmallIcon(R.drawable.ic_stat_custom);
    // END_INCLUDE(ticker)

    // BEGIN_INCLUDE(buildNotification)
    // Cancel the notification when clicked
    builder.setAutoCancel(true);

    // Build the notification
    Notification notification = builder.build();
    // END_INCLUDE(buildNotification)

    // BEGIN_INCLUDE(customLayout)
    // Inflate the notification layout as RemoteViews
    RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.notification);

    // Set text on a TextView in the RemoteViews programmatically.
    final String time = DateFormat.getTimeInstance().format(new Date()).toString();
    final String text = getResources().getString(R.string.collapsed, time);
    contentView.setTextViewText(R.id.textView, text);

    /* Workaround: Need to set the content view here directly on the notification.
     * NotificationCompatBuilder contains a bug that prevents this from working on platform
     * versions HoneyComb.
     * See https://code.google.com/p/android/issues/detail?id=30495
     */
    notification.contentView = contentView;

    // Add a big content view to the notification if supported.
    // Support for expanded notifications was added in API level 16.
    // (The normal contentView is shown when the notification is collapsed, when expanded the
    // big content view set here is displayed.)
    if (Build.VERSION.SDK_INT >= 16) {
        // Inflate and set the layout for the expanded notification view
        RemoteViews expandedView = new RemoteViews(getPackageName(), R.layout.notification_expanded);
        notification.bigContentView = expandedView;
    }
    // END_INCLUDE(customLayout)

    // START_INCLUDE(notify)
    // Use the NotificationManager to show the notification
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.notify(0, notification);
    // END_INCLUDE(notify)
}

From source file:org.kde.kdeconnect.Plugins.MprisPlugin.NotificationPanel.java

public NotificationPanel(Context context, Device device, String player) {
    this.deviceId = device.getDeviceId();
    this.player = player;

    //FIXME: When the mpris plugin gets destroyed and recreated, we should add this listener again
    final MprisPlugin mpris = (MprisPlugin) device.getPlugin("plugin_mpris");
    if (mpris != null) {
        mpris.setPlayerStatusUpdatedHandler("notification", new Handler() {
            @Override//w w  w. j  a  va2s. c  o m
            public void handleMessage(Message msg) {
                String song = mpris.getCurrentSong();
                boolean isPlaying = mpris.isPlaying();
                updateStatus(song, isPlaying);
            }
        });
    }

    Intent launch = new Intent(context, MprisActivity.class);
    launch.putExtra("deviceId", deviceId);
    launch.putExtra("player", player);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MprisActivity.class);
    stackBuilder.addNextIntent(launch);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    nManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    remoteView = new RemoteViews(context.getPackageName(), R.layout.mpris_notification);
    nBuilder = new NotificationCompat.Builder(context).setContentTitle("KDE Connect").setLocalOnly(true)
            .setSmallIcon(android.R.drawable.ic_media_play).setContentIntent(resultPendingIntent)
            .setOngoing(true);

    String deviceName = device.getName();
    String playerOnDevice = context.getString(R.string.mpris_player_on_device, player, deviceName);
    remoteView.setTextViewText(R.id.notification_player, playerOnDevice);

    Intent playpause = new Intent(context, NotificationReturnSlot.class);
    playpause.putExtra("action", "play");
    playpause.putExtra("deviceId", deviceId);
    playpause.putExtra("player", player);
    PendingIntent btn1 = PendingIntent.getBroadcast(context, NotificationsHelper.getUniqueId(), playpause, 0);
    remoteView.setOnClickPendingIntent(R.id.notification_play_pause, btn1);

    Intent next = new Intent(context, NotificationReturnSlot.class);
    next.putExtra("action", "next");
    next.putExtra("deviceId", deviceId);
    next.putExtra("player", player);
    PendingIntent btn2 = PendingIntent.getBroadcast(context, NotificationsHelper.getUniqueId(), next, 0);
    remoteView.setOnClickPendingIntent(R.id.notification_next, btn2);

    Intent prev = new Intent(context, NotificationReturnSlot.class);
    prev.putExtra("action", "prev");
    prev.putExtra("deviceId", deviceId);
    prev.putExtra("player", player);
    PendingIntent btn3 = PendingIntent.getBroadcast(context, NotificationsHelper.getUniqueId(), prev, 0);
    remoteView.setOnClickPendingIntent(R.id.notification_prev, btn3);

    nBuilder.setContent(remoteView);
    nManager.notify(notificationId, nBuilder.build());
}

From source file:com.teclib.service.NotificationAdminRequest.java

public void CustomNotification() {
    RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notification_install_apps);

    Intent intent = new Intent(this, MQTTNotifierActivity.class);

    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_white_stork).setTicker(getString(R.string.installAsk_string))
            .setOngoing(true).setContentIntent(pIntent).setAutoCancel(true).setContent(remoteViews);

    Notification notificationInstall = builder.build();
    notificationInstall.flags |= Notification.FLAG_AUTO_CANCEL;

    remoteViews.setImageViewResource(R.id.imagenotileft, R.mipmap.ic_notification_install_apps);

    remoteViews.setTextViewText(R.id.title, getString(R.string.app_name));
    remoteViews.setTextViewText(R.id.text, getString(R.string.installAsk_string));

    NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    notificationmanager.notify(6, builder.build());

}

From source file:com.fbartnitzek.tasteemall.widget.StatsWidgetIntentService.java

@Override
protected void onHandleIntent(Intent intent) {

    //        Log.v(LOG_TAG, "onHandleIntent, hashCode=" + this.hashCode() + ", " + "intent = [" + intent + "]");

    // get all widget ids
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(this, StatsWidgetProvider.class));

    // query all entities
    int numLocations = queryAndGetCount(DatabaseContract.LocationEntry.CONTENT_URI,
            QueryColumns.Widget.LocationQuery.COLUMNS);
    int numProducers = queryAndGetCount(DatabaseContract.ProducerEntry.CONTENT_URI,
            QueryColumns.Widget.ProviderQuery.COLUMNS);
    int numDrinks = queryAndGetCount(DatabaseContract.DrinkEntry.CONTENT_URI,
            QueryColumns.Widget.DrinkQuery.COLUMNS);
    int numUsers = queryAndGetCount(DatabaseContract.UserEntry.CONTENT_URI,
            QueryColumns.Widget.UserQuery.COLUMNS);
    int numReviews = queryAndGetCount(DatabaseContract.ReviewEntry.CONTENT_URI,
            QueryColumns.Widget.ReviewQuery.COLUMNS);

    // TODO: results are getting "cached" or something like that ...
    // maybe that helps: http://stackoverflow.com/questions/9497270/widget-with-content-provider-impossible-to-use-readpermission
    Log.v(LOG_TAG,/*from  w w w  . java2 s .c  o m*/
            "onHandleIntent, producer=" + numProducers + ", drinks=" + numDrinks + ", reviews=" + numReviews);

    for (int appWidgetId : appWidgetIds) {
        // dynamically adapt widget width ... later

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

        // fill stats
        views.setTextViewText(R.id.stats_locations,
                getString(R.string.widget_statistics_locations, numLocations));

        views.setTextViewText(R.id.stats_producers,
                getString(R.string.widget_statistics_producers, numProducers));

        views.setTextViewText(R.id.stats_drinks, getString(R.string.widget_statistics_drinks, numDrinks));

        views.setTextViewText(R.id.stats_users, getString(R.string.widget_statistics_users, numUsers));

        views.setTextViewText(R.id.stats_reviews, getString(R.string.widget_statistics_reviews, numReviews));

        // seems to be impossible to get contentDescription for whole widget...
        //            views.setContentDescription(R.id.widget_layout,
        //                    getString(R.string.a11y_widget_statistics_all, numProducers, numDrinks, numReviews));

        views.setContentDescription(R.id.stats_reviews,
                getString(R.string.a11y_widget_statistics_all, numProducers, numDrinks, numReviews));

        // set on click listener for add and search on every update (kind of useless...)

        // add button - create backStack for add
        Intent addIntent = new Intent(this, AddReviewActivity.class);
        PendingIntent addPendingIntent = TaskStackBuilder.create(this).addNextIntentWithParentStack(addIntent)
                .getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setOnClickPendingIntent(R.id.widget_add_button, addPendingIntent);

        // search button
        PendingIntent searchPendingIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, MainActivity.class), 0);
        views.setOnClickPendingIntent(R.id.widget_search_button, searchPendingIntent);

        // update each StatsWidget
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
}

From source file:github.popeen.dsub.util.Notifications.java

public static void showPlayingNotification(final Context context, final DownloadService downloadService,
        final Handler handler, MusicDirectory.Entry song) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        getPlayingNotificationChannel(context);
    }//from www. j ava2  s  .  co m

    // Set the icon, scrolling text and timestamp
    final Notification notification = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.stat_notify_playing).setTicker(song.getTitle())
            .setWhen(System.currentTimeMillis()).setChannelId("now-playing-channel").build();

    final boolean playing = downloadService.getPlayerState() == PlayerState.STARTED;
    if (playing) {
        notification.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
    }
    boolean remote = downloadService.isRemoteEnabled();
    boolean isSingle = downloadService.isCurrentPlayingSingle();
    boolean shouldFastForward = true;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        RemoteViews expandedContentView = new RemoteViews(context.getPackageName(),
                R.layout.notification_expanded);
        setupViews(expandedContentView, context, song, true, playing, remote, isSingle, shouldFastForward);
        notification.bigContentView = expandedContentView;
        notification.priority = Notification.PRIORITY_HIGH;
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        notification.visibility = Notification.VISIBILITY_PUBLIC;

        if (Util.getPreferences(context).getBoolean(Constants.PREFERENCES_KEY_HEADS_UP_NOTIFICATION, false)
                && !UpdateView.hasActiveActivity()) {
            notification.vibrate = new long[0];
        }
    }

    RemoteViews smallContentView = new RemoteViews(context.getPackageName(), R.layout.notification);
    setupViews(smallContentView, context, song, false, playing, remote, isSingle, shouldFastForward);
    notification.contentView = smallContentView;

    Intent notificationIntent = new Intent(context, SubsonicFragmentActivity.class);
    notificationIntent.putExtra(Constants.INTENT_EXTRA_NAME_DOWNLOAD, true);

    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    notification.contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    playShowing = true;
    if (downloadForeground && downloadShowing) {
        downloadForeground = false;
        handler.post(new Runnable() {
            @Override
            public void run() {
                stopForeground(downloadService, true);
                showDownloadingNotification(context, downloadService, handler,
                        downloadService.getCurrentDownloading(),
                        downloadService.getBackgroundDownloads().size());

                try {
                    startForeground(downloadService, NOTIFICATION_ID_PLAYING, notification);
                } catch (Exception e) {
                    Log.e(TAG, "Failed to start notifications after stopping foreground download");
                }
            }
        });
    } else {
        handler.post(new Runnable() {
            @Override
            public void run() {

                if (playing) {
                    try {
                        startForeground(downloadService, NOTIFICATION_ID_PLAYING, notification);
                    } catch (Exception e) {
                        Log.e(TAG, "Failed to start notifications while playing");
                    }
                } else {
                    playShowing = false;
                    persistentPlayingShowing = true;
                    NotificationManager notificationManager = (NotificationManager) context
                            .getSystemService(Context.NOTIFICATION_SERVICE);
                    stopForeground(downloadService, false);

                    try {
                        notificationManager.notify(NOTIFICATION_ID_PLAYING, notification);
                    } catch (Exception e) {
                        Log.e(TAG, "Failed to start notifications while paused");
                    }
                }
            }
        });
    }

    // Update widget
    DSubWidgetProvider.notifyInstances(context, downloadService, playing);
}

From source file:dk.cafeanalog.AnalogWidget.java

private void handleError(Context mContext) {
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(mContext);
    RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.analog_widget);
    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(mContext, AnalogWidget.class));
    views.setTextViewText(R.id.appwidget_text, "Error");
    views.setOnClickPendingIntent(R.id.appwidget_text, getPendingSelfIntent(mContext));
    // Instruct the widget manager to update the widget
    for (int appWidgetId : appWidgetIds) {
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }//from   ww  w .  j  ava  2s  .c o m
}

From source file:com.abhijitvalluri.android.fitnotifications.widget.ServiceToggle.java

@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);

    if (TOGGLE_CLICKED.equals(intent.getAction())) {
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.service_toggle_widget);
        if (NLService.isEnabled()) {
            NLService.setEnabled(false);
            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));
        } else {//from w ww  . j a  v a2 s .c  o m
            NLService.setEnabled(true);
            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));
        }

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

        ComponentName componentName = new ComponentName(context, ServiceToggle.class);
        appWidgetManager.updateAppWidget(componentName, views);
    }
}