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:com.open.file.manager.CutCopyService.java

@Override
protected void onHandleIntent(Intent intent) {
    progressview = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbarlayout);

    currentaction = intent.getIntExtra("action", 0);
    filelist = intent.getStringArrayListExtra("filelist");
    targetfolder = new File(intent.getStringExtra("targetfolder"));
    tree = new FileCopyTree(filelist, targetfolder);
    duplicates = null;//from ww  w.  j a  v a 2  s .c om
    currentfileind = 0;
    progressbytes = 0;
    progresspercent = 0;
    totalbytes = tree.size;
    mHandler = new dupresponcehandler(this);
    if (tree.duplicates.size() != 0) {
        sendDuplicateMessage();
    }
    id = 1;
    completeid = (completeid + 2) % Integer.MAX_VALUE;
    cutcopymanager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    cutcopybuilder = new NotificationCompat.Builder(this);
    // cutcopybuilder.setProgress(100, 0, false);

    Intent notificationIntent = new Intent(this, MainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    cutcopybuilder
            .setContent(new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbarlayout));
    cutcopybuilder.setSmallIcon(R.drawable.notifyicon);
    actiongerund = getResources().getString(actioning[currentaction]);
    cutcopybuilder.setContentTitle(actiongerund + " files");
    cutcopybuilder.setContentIntent(contentIntent);
    cutcopynotification = cutcopybuilder.build();
    cutcopynotification.contentView = progressview;
    cutcopynotification.contentView.setProgressBar(R.id.progressBar, 100, 0, false);
    cutcopynotification.contentView.setTextViewText(R.id.progresstext, actiongerund + " files");
    cutcopymanager.notify(id, cutcopynotification);
    startForeground(id, cutcopynotification);
    performCutCopy();
}

From source file:air.com.snagfilms.cast.chromecast.notifications.VideoCastNotificationService.java

private RemoteViews build(MediaInfo info, Bitmap bitmap, boolean isPlaying, Class<?> targetActivity)
        throws CastException, TransientNetworkDisconnectionException, NoConnectionException {
    Bundle mediaWrapper = Utils.fromMediaInfo(mCastManager.getRemoteMediaInformation());
    Intent contentIntent = null;//from   w w w.j  a  va 2s  . c  om
    if (null == mTargetActivity) {
        mTargetActivity = VideoPlayerActivity.class;
    }
    contentIntent = new Intent(this, mTargetActivity);

    contentIntent.putExtra("media", mediaWrapper);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    stackBuilder.addParentStack(mTargetActivity);

    stackBuilder.addNextIntent(contentIntent);
    if (stackBuilder.getIntentCount() > 1) {
        stackBuilder.editIntentAt(1).putExtra("media", mediaWrapper);
    }

    // Gets a PendingIntent containing the entire back stack
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(NOTIFICATION_ID,
            PendingIntent.FLAG_UPDATE_CURRENT);

    MediaMetadata mm = info.getMetadata();

    RemoteViews rv = new RemoteViews(getPackageName(), R.layout.custom_notification);
    if (mIsIcsOrAbove) {
        addPendingIntents(rv, isPlaying, info);
    }
    if (null != bitmap) {
        rv.setImageViewBitmap(R.id.iconView, bitmap);
    }
    rv.setTextViewText(R.id.titleView, mm.getString(MediaMetadata.KEY_TITLE));
    String castingTo = getResources().getString(R.string.casting_to_device, mCastManager.getDeviceName());
    rv.setTextViewText(R.id.subTitleView, castingTo);
    mNotification = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_stat_action_notification)
            .setContentIntent(resultPendingIntent).setContent(rv).setAutoCancel(false).setOngoing(true).build();

    // to get around a bug in GB version, we add the following line
    // see https://code.google.com/p/android/issues/detail?id=30495
    mNotification.contentView = rv;

    return rv;
}

From source file:com.tingtingapps.securesms.service.KeyCachingService.java

private void foregroundServiceICS() {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    RemoteViews remoteViews = new RemoteViews(getPackageName(),
            com.tingtingapps.securesms.R.layout.key_caching_notification);

    remoteViews.setOnClickPendingIntent(com.tingtingapps.securesms.R.id.lock_cache_icon, buildLockIntent());

    builder.setSmallIcon(com.tingtingapps.securesms.R.drawable.icon_cached);
    builder.setContent(remoteViews);/*from w  w  w.  ja  va 2  s .  c  o  m*/
    builder.setContentIntent(buildLaunchIntent());

    stopForeground(true);
    startForeground(SERVICE_RUNNING_ID, builder.build());
}

From source file:com.wizardsofm.deskclock.data.TimerNotificationBuilderN.java

@Override
public Notification buildHeadsUp(Context context, List<Timer> expired) {
    final Timer timer = expired.get(0);

    // First action intent is to reset all timers.
    final Icon icon1 = Icon.createWithResource(context, com.wizardsofm.deskclock.R.drawable.ic_stop_24dp);
    final Intent reset = TimerService.createResetExpiredTimersIntent(context);
    final PendingIntent intent1 = Utils.pendingServiceIntent(context, reset);

    // Generate some descriptive text, a title, and an action name based on the timer count.
    final CharSequence stateText;
    final int count = expired.size();
    final List<Notification.Action> actions = new ArrayList<>(2);
    if (count == 1) {
        final String label = timer.getLabel();
        if (TextUtils.isEmpty(label)) {
            stateText = context.getString(com.wizardsofm.deskclock.R.string.timer_times_up);
        } else {/*  w w  w  .  j a v a 2  s  . c om*/
            stateText = label;
        }

        // Left button: Reset single timer
        final CharSequence title1 = context.getString(com.wizardsofm.deskclock.R.string.timer_stop);
        actions.add(new Notification.Action.Builder(icon1, title1, intent1).build());

        // Right button: Add minute
        final Intent addTime = TimerService.createAddMinuteTimerIntent(context, timer.getId());
        final PendingIntent intent2 = Utils.pendingServiceIntent(context, addTime);
        final Icon icon2 = Icon.createWithResource(context, com.wizardsofm.deskclock.R.drawable.ic_add_24dp);
        final CharSequence title2 = context.getString(com.wizardsofm.deskclock.R.string.timer_plus_1_min);
        actions.add(new Notification.Action.Builder(icon2, title2, intent2).build());

    } else {
        stateText = context.getString(com.wizardsofm.deskclock.R.string.timer_multi_times_up, count);

        // Left button: Reset all timers
        final CharSequence title1 = context.getString(com.wizardsofm.deskclock.R.string.timer_stop_all);
        actions.add(new Notification.Action.Builder(icon1, title1, intent1).build());
    }

    final long base = getChronometerBase(timer);

    final String pname = context.getPackageName();
    final RemoteViews contentView = new RemoteViews(pname,
            com.wizardsofm.deskclock.R.layout.chronometer_notif_content);
    contentView.setChronometerCountDown(com.wizardsofm.deskclock.R.id.chronometer, true);
    contentView.setChronometer(com.wizardsofm.deskclock.R.id.chronometer, base, null, true);
    contentView.setTextViewText(com.wizardsofm.deskclock.R.id.state, stateText);

    // Content intent shows the timer full screen when clicked.
    final Intent content = new Intent(context, ExpiredTimersActivity.class);
    final PendingIntent contentIntent = Utils.pendingActivityIntent(context, content);

    // Full screen intent has flags so it is different than the content intent.
    final Intent fullScreen = new Intent(context, ExpiredTimersActivity.class)
            .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
    final PendingIntent pendingFullScreen = Utils.pendingActivityIntent(context, fullScreen);

    return new Notification.Builder(context).setOngoing(true).setLocalOnly(true).setShowWhen(false)
            .setAutoCancel(false).setContentIntent(contentIntent).setCustomContentView(contentView)
            .setPriority(Notification.PRIORITY_MAX).setDefaults(Notification.DEFAULT_LIGHTS)
            .setColor(ContextCompat.getColor(context, com.wizardsofm.deskclock.R.color.default_background))
            .setSmallIcon(com.wizardsofm.deskclock.R.drawable.stat_notify_timer)
            .setFullScreenIntent(pendingFullScreen, true).setStyle(new Notification.DecoratedCustomViewStyle())
            .setActions(actions.toArray(new Notification.Action[actions.size()])).build();
}

From source file:com.syncedsynapse.kore2.service.NotificationService.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void buildNotification(PlayerType.GetActivePlayersReturnType getActivePlayerResult,
        PlayerType.PropertyValue getPropertiesResult, ListType.ItemsAll getItemResult) {
    final String title, underTitle, poster;
    int smallIcon, playPauseIcon, rewindIcon, ffIcon;

    boolean isVideo = ((getItemResult.type.equals(ListType.ItemsAll.TYPE_MOVIE))
            || (getItemResult.type.equals(ListType.ItemsAll.TYPE_EPISODE)));

    switch (getItemResult.type) {
    case ListType.ItemsAll.TYPE_MOVIE:
        title = getItemResult.title;//from  w w w .  j ava  2  s. c om
        underTitle = getItemResult.tagline;
        poster = getItemResult.thumbnail;
        smallIcon = R.drawable.ic_movie_white_24dp;
        break;
    case ListType.ItemsAll.TYPE_EPISODE:
        title = getItemResult.title;
        String seasonEpisode = String.format(getString(R.string.season_episode_abbrev), getItemResult.season,
                getItemResult.episode);
        underTitle = String.format("%s | %s", getItemResult.showtitle, seasonEpisode);
        poster = getItemResult.art.poster;
        smallIcon = R.drawable.ic_tv_white_24dp;
        break;
    case ListType.ItemsAll.TYPE_SONG:
        title = getItemResult.title;
        underTitle = getItemResult.displayartist + " | " + getItemResult.album;
        poster = getItemResult.thumbnail;
        smallIcon = R.drawable.ic_headset_white_24dp;
        break;
    case ListType.ItemsAll.TYPE_MUSIC_VIDEO:
        title = getItemResult.title;
        underTitle = Utils.listStringConcat(getItemResult.artist, ", ") + " | " + getItemResult.album;
        poster = getItemResult.thumbnail;
        smallIcon = R.drawable.ic_headset_white_24dp;
        break;
    default:
        // We don't know what this is, forget it
        return;
    }

    switch (getPropertiesResult.speed) {
    case 1:
        playPauseIcon = R.drawable.ic_pause_white_24dp;
        break;
    default:
        playPauseIcon = R.drawable.ic_play_arrow_white_24dp;
        break;
    }

    // Create the actions, depending on the type of media
    PendingIntent rewindPendingItent, ffPendingItent, playPausePendingIntent;
    playPausePendingIntent = buildActionPendingIntent(getActivePlayerResult.playerid,
            IntentActionsService.ACTION_PLAY_PAUSE);
    if (getItemResult.type.equals(ListType.ItemsAll.TYPE_SONG)) {
        rewindPendingItent = buildActionPendingIntent(getActivePlayerResult.playerid,
                IntentActionsService.ACTION_PREVIOUS);
        rewindIcon = R.drawable.ic_skip_previous_white_24dp;
        ffPendingItent = buildActionPendingIntent(getActivePlayerResult.playerid,
                IntentActionsService.ACTION_NEXT);
        ffIcon = R.drawable.ic_skip_next_white_24dp;
    } else {
        rewindPendingItent = buildActionPendingIntent(getActivePlayerResult.playerid,
                IntentActionsService.ACTION_REWIND);
        rewindIcon = R.drawable.ic_fast_rewind_white_24dp;
        ffPendingItent = buildActionPendingIntent(getActivePlayerResult.playerid,
                IntentActionsService.ACTION_FAST_FORWARD);
        ffIcon = R.drawable.ic_fast_forward_white_24dp;
    }

    // Setup the collpased and expanded notifications
    final RemoteViews collapsedRV = new RemoteViews(this.getPackageName(), R.layout.notification_colapsed);
    collapsedRV.setImageViewResource(R.id.rewind, rewindIcon);
    collapsedRV.setOnClickPendingIntent(R.id.rewind, rewindPendingItent);
    collapsedRV.setImageViewResource(R.id.play, playPauseIcon);
    collapsedRV.setOnClickPendingIntent(R.id.play, playPausePendingIntent);
    collapsedRV.setImageViewResource(R.id.fast_forward, ffIcon);
    collapsedRV.setOnClickPendingIntent(R.id.fast_forward, ffPendingItent);
    collapsedRV.setTextViewText(R.id.title, title);
    collapsedRV.setTextViewText(R.id.text2, underTitle);

    final RemoteViews expandedRV = new RemoteViews(this.getPackageName(), R.layout.notification_expanded);
    expandedRV.setImageViewResource(R.id.rewind, rewindIcon);
    expandedRV.setOnClickPendingIntent(R.id.rewind, rewindPendingItent);
    expandedRV.setImageViewResource(R.id.play, playPauseIcon);
    expandedRV.setOnClickPendingIntent(R.id.play, playPausePendingIntent);
    expandedRV.setImageViewResource(R.id.fast_forward, ffIcon);
    expandedRV.setOnClickPendingIntent(R.id.fast_forward, ffPendingItent);
    expandedRV.setTextViewText(R.id.title, title);
    expandedRV.setTextViewText(R.id.text2, underTitle);
    final int expandedIconResId;
    if (isVideo) {
        expandedIconResId = R.id.icon_slim;
        expandedRV.setViewVisibility(R.id.icon_slim, View.VISIBLE);
        expandedRV.setViewVisibility(R.id.icon_square, View.GONE);
    } else {
        expandedIconResId = R.id.icon_square;
        expandedRV.setViewVisibility(R.id.icon_slim, View.GONE);
        expandedRV.setViewVisibility(R.id.icon_square, View.VISIBLE);
    }

    // Build the notification
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    final Notification notification = builder.setSmallIcon(smallIcon).setShowWhen(false).setOngoing(true)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setCategory(NotificationCompat.CATEGORY_TRANSPORT).setContentIntent(mRemoteStartPendingIntent)
            .setContent(collapsedRV).build();

    // This is a convoluted way of loading the image and showing the
    // notification, but it's what works with Picasso and is efficient.
    // Here's what's going on:
    //
    // 1. The image is loaded asynchronously into a Target, and only after
    // it is loaded is the notification shown. Using targets is a lot more
    // efficient than letting Picasso load it directly into the
    // notification imageview, which causes a lot of flickering
    //
    // 2. The target needs to be static, because Picasso only keeps a weak
    // reference to it, so we need to keed a strong reference and reset it
    // to null when we're done. We also need to check if it is not null in
    // case a previous request hasn't finished yet.
    //
    // 3. We can only show the notification after the bitmap is loaded into
    // the target, so it is done in the callback
    //
    // 4. We specifically resize the image to the same dimensions used in
    // the remote, so that Picasso reuses it in the remote and here from the cache
    Resources resources = this.getResources();
    final int posterWidth = resources.getDimensionPixelOffset(R.dimen.now_playing_poster_width);
    final int posterHeight = isVideo ? resources.getDimensionPixelOffset(R.dimen.now_playing_poster_height)
            : posterWidth;
    if (picassoTarget == null) {
        picassoTarget = new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                showNotification(bitmap);
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
                CharacterDrawable avatarDrawable = UIUtils.getCharacterAvatar(NotificationService.this, title);
                showNotification(Utils.drawableToBitmap(avatarDrawable, posterWidth, posterHeight));
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
            }

            private void showNotification(Bitmap bitmap) {
                collapsedRV.setImageViewBitmap(R.id.icon, bitmap);
                if (Utils.isJellybeanOrLater()) {
                    notification.bigContentView = expandedRV;
                    expandedRV.setImageViewBitmap(expandedIconResId, bitmap);
                }

                NotificationManager notificationManager = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                notificationManager.notify(NOTIFICATION_ID, notification);
                picassoTarget = null;
            }
        };

        // Load the image
        HostManager hostManager = HostManager.getInstance(this);
        hostManager.getPicasso().load(hostManager.getHostInfo().getImageUrl(poster))
                .resize(posterWidth, posterHeight).into(picassoTarget);
    }
}

From source file:com.elekso.potfix.MainActivity.java

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);/* w  w  w.  ja  va2s .  co  m*/
    // 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.icon4_1);
    // 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:com.devbrackets.android.playlistcore.helper.NotificationHelper.java

/**
 * Creates the RemoteViews used for the custom (standard) notification
 *
 * @return The resulting RemoteViews/*from  w  w  w  .j  a v  a2s .  c  o  m*/
 */
@NonNull
protected RemoteViews getCustomNotification(@NonNull Class<? extends Service> serviceClass) {
    RemoteViews customNotification = new RemoteViews(context.getPackageName(),
            R.layout.playlistcore_notification_content);

    customNotification.setOnClickPendingIntent(R.id.playlistcore_notification_playpause,
            createPendingIntent(RemoteActions.ACTION_PLAY_PAUSE, serviceClass));
    customNotification.setOnClickPendingIntent(R.id.playlistcore_notification_next,
            createPendingIntent(RemoteActions.ACTION_NEXT, serviceClass));
    customNotification.setOnClickPendingIntent(R.id.playlistcore_notification_prev,
            createPendingIntent(RemoteActions.ACTION_PREVIOUS, serviceClass));

    customNotification.setTextViewText(R.id.playlistcore_notification_title, notificationInfo.getTitle());
    customNotification.setTextViewText(R.id.playlistcore_notification_album, notificationInfo.getAlbum());
    customNotification.setTextViewText(R.id.playlistcore_notification_artist, notificationInfo.getArtist());
    if (notificationInfo.getLargeImage() != null) {
        customNotification.setBitmap(R.id.playlistcore_notification_large_image, "setImageBitmap",
                notificationInfo.getLargeImage());
    }

    if (notificationInfo.getMediaState() != null) {
        updateCustomNotificationMediaState(customNotification);
    }

    return customNotification;
}

From source file:com.firefly.sample.castcompanionlibrary.notification.VideoCastNotificationService.java

private RemoteViews build(MediaInfo info, Bitmap bitmap, boolean isPlaying, Class<?> targetActivity)
        throws CastException, TransientNetworkDisconnectionException, NoConnectionException {
    Bundle mediaWrapper = Utils.fromMediaInfo(mCastManager.getRemoteMediaInformation());
    Intent contentIntent = null;/*from   w ww .j a  v  a  2s.c om*/
    if (null == mTargetActivity) {
        mTargetActivity = VideoCastControllerActivity.class;
    }
    contentIntent = new Intent(this, mTargetActivity);

    contentIntent.putExtra("media", mediaWrapper);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    stackBuilder.addParentStack(mTargetActivity);

    stackBuilder.addNextIntent(contentIntent);
    if (stackBuilder.getIntentCount() > 1) {
        stackBuilder.editIntentAt(1).putExtra("media", mediaWrapper);
    }

    // Gets a PendingIntent containing the entire back stack
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(NOTIFICATION_ID,
            PendingIntent.FLAG_UPDATE_CURRENT);

    MediaMetadata mm = info.getMetadata();

    RemoteViews rv = new RemoteViews(getPackageName(), R.layout.custom_notification);
    if (mIsIcsOrAbove) {
        addPendingIntents(rv, isPlaying, info);
    }
    if (null != bitmap) {
        rv.setImageViewBitmap(R.id.iconView, bitmap);
    }
    rv.setTextViewText(R.id.titleView, mm.getString(MediaMetadata.KEY_TITLE));
    String castingTo = getResources().getString(R.string.casting_to_device, mCastManager.getDeviceName());
    rv.setTextViewText(R.id.subTitleView, castingTo);
    mNotification = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_stat_action_notification)
            .setContentIntent(resultPendingIntent).setContent(rv).setAutoCancel(false).setOngoing(true).build();

    // to get around a bug in GB version, we add the following line
    // see https://code.google.com/p/android/issues/detail?id=30495
    mNotification.contentView = rv;

    return rv;
}

From source file:org.gnucash.android.ui.homescreen.WidgetConfigurationActivity.java

/**
 * Updates the widget with id <code>appWidgetId</code> with information from the 
 * account with record ID <code>accountId</code>
  * If the account has been deleted, then a notice is posted in the widget
 * @param appWidgetId ID of the widget to be updated
 *//*from  w  ww. j  a va  2  s .c  o m*/
public static void updateWidget(final Context context, int appWidgetId) {
    Log.i("WidgetConfiguration", "Updating widget: " + appWidgetId);
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

    loadOldPreferences(context, appWidgetId);

    SharedPreferences preferences = context.getSharedPreferences("widget:" + appWidgetId, MODE_PRIVATE);
    String bookUID = preferences.getString(UxArgument.BOOK_UID, null);
    String accountUID = preferences.getString(UxArgument.SELECTED_ACCOUNT_UID, null);
    boolean hideAccountBalance = preferences.getBoolean(UxArgument.HIDE_ACCOUNT_BALANCE_IN_WIDGET, false);

    if (bookUID == null || accountUID == null) {
        return;
    }

    AccountsDbAdapter accountsDbAdapter = new AccountsDbAdapter(BookDbHelper.getDatabase(bookUID));

    final Account account;
    try {
        account = accountsDbAdapter.getRecord(accountUID);
    } catch (IllegalArgumentException e) {
        Log.i("WidgetConfiguration", "Account not found, resetting widget " + appWidgetId);
        //if account has been deleted, let the user know
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_4x1);
        views.setTextViewText(R.id.account_name, context.getString(R.string.toast_account_deleted));
        views.setTextViewText(R.id.transactions_summary, "");
        //set it to simply open the app
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
                new Intent(context, AccountsActivity.class), 0);
        views.setOnClickPendingIntent(R.id.widget_layout, pendingIntent);
        views.setOnClickPendingIntent(R.id.btn_new_transaction, pendingIntent);
        appWidgetManager.updateAppWidget(appWidgetId, views);
        Editor editor = PreferenceActivity.getActiveBookSharedPreferences().edit(); //PreferenceManager.getDefaultSharedPreferences(context).edit();
        editor.remove(UxArgument.SELECTED_ACCOUNT_UID + appWidgetId);
        editor.apply();
        return;
    }

    final RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_4x1);
    views.setTextViewText(R.id.account_name, account.getName());

    Money accountBalance = accountsDbAdapter.getAccountBalance(accountUID, -1, System.currentTimeMillis());

    if (hideAccountBalance) {
        views.setViewVisibility(R.id.transactions_summary, View.GONE);
    } else {
        views.setTextViewText(R.id.transactions_summary, accountBalance.formattedString(Locale.getDefault()));
        int color = accountBalance.isNegative() ? R.color.debit_red : R.color.credit_green;
        views.setTextColor(R.id.transactions_summary, context.getResources().getColor(color));
    }

    Intent accountViewIntent = new Intent(context, TransactionsActivity.class);
    accountViewIntent.setAction(Intent.ACTION_VIEW);
    accountViewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    accountViewIntent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, accountUID);
    accountViewIntent.putExtra(UxArgument.BOOK_UID, bookUID);
    PendingIntent accountPendingIntent = PendingIntent.getActivity(context, appWidgetId, accountViewIntent, 0);
    views.setOnClickPendingIntent(R.id.widget_layout, accountPendingIntent);

    if (accountsDbAdapter.isPlaceholderAccount(accountUID)) {
        views.setOnClickPendingIntent(R.id.btn_view_account, accountPendingIntent);
        views.setViewVisibility(R.id.btn_new_transaction, View.GONE);
    } else {
        Intent newTransactionIntent = new Intent(context, FormActivity.class);
        newTransactionIntent.setAction(Intent.ACTION_INSERT_OR_EDIT);
        newTransactionIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        newTransactionIntent.putExtra(UxArgument.FORM_TYPE, FormActivity.FormType.TRANSACTION.name());
        newTransactionIntent.putExtra(UxArgument.BOOK_UID, bookUID);
        newTransactionIntent.putExtra(UxArgument.SELECTED_ACCOUNT_UID, accountUID);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, appWidgetId, newTransactionIntent, 0);
        views.setOnClickPendingIntent(R.id.btn_new_transaction, pendingIntent);
        views.setViewVisibility(R.id.btn_view_account, View.GONE);
    }

    appWidgetManager.updateAppWidget(appWidgetId, views);
}

From source file:com.racoon.ampdroid.Mp3PlayerService.java

private void setNotifiction() {
    RemoteViews notificationView = new RemoteViews(this.getPackageName(), R.layout.player_notification);
    notificationView.setTextViewText(R.id.notificationSongArtist, getArtist());
    notificationView.setTextViewText(R.id.notificationSongTitle, getCurrentTitle());
    /* 1. Setup Notification Builder */
    Notification.Builder builder = new Notification.Builder(this);

    /* 2. Configure Notification Alarm */
    builder.setSmallIcon(R.drawable.ic_stat_notify).setAutoCancel(true).setWhen(System.currentTimeMillis())
            .setTicker(getCurrentTitle());

    Intent intent = new Intent(this, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent notifIntent = PendingIntent.getActivity(this, 0, intent, 0);

    builder.setContentIntent(notifIntent);
    builder.setContent(notificationView);

    /* 4. Create Notification and use Manager to launch it */
    Notification notification = builder.getNotification();
    String ns = Context.NOTIFICATION_SERVICE;
    notifManager = (NotificationManager) getSystemService(ns);
    notifManager.notify(NOTIFICATION_ID, notification);
    startForeground(NOTIFICATION_ID, notification);
}