Example usage for android.widget RemoteViews setTextViewText

List of usage examples for android.widget RemoteViews setTextViewText

Introduction

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

Prototype

public void setTextViewText(int viewId, CharSequence text) 

Source Link

Document

Equivalent to calling TextView#setText(CharSequence)

Usage

From source file:RhodesService.java

private void updateDownloadNotification(String url, int totalBytes, int currentBytes) {
    Context context = RhodesActivity.getContext();

    Notification n = new Notification();
    n.icon = android.R.drawable.stat_sys_download;
    n.flags |= Notification.FLAG_ONGOING_EVENT;

    RemoteViews expandedView = new RemoteViews(context.getPackageName(),
            R.layout.status_bar_ongoing_event_progress_bar);

    StringBuilder newUrl = new StringBuilder();
    if (url.length() < 17)
        newUrl.append(url);//from www.ja  v  a 2s  .c o m
    else {
        newUrl.append(url.substring(0, 7));
        newUrl.append("...");
        newUrl.append(url.substring(url.length() - 7, url.length()));
    }
    expandedView.setTextViewText(R.id.title, newUrl.toString());

    StringBuffer downloadingText = new StringBuffer();
    if (totalBytes > 0) {
        long progress = currentBytes * 100 / totalBytes;
        downloadingText.append(progress);
        downloadingText.append('%');
    }
    expandedView.setTextViewText(R.id.progress_text, downloadingText.toString());
    expandedView.setProgressBar(R.id.progress_bar, totalBytes < 0 ? 100 : totalBytes, currentBytes,
            totalBytes < 0);
    n.contentView = expandedView;

    Intent intent = new Intent(ACTION_ASK_CANCEL_DOWNLOAD);
    n.contentIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
    intent = new Intent(ACTION_CANCEL_DOWNLOAD);
    n.deleteIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    mNM.notify(DOWNLOAD_PACKAGE_ID, n);
}

From source file:com.namelessdev.mpdroid.NotificationService.java

/**
 * This method builds the base, otherwise known as the collapsed notification. The expanded
 * notification method builds upon this method.
 *
 * @param resultView The RemoteView to begin with, be it new or from the current notification.
 * @return The base, otherwise known as, collapsed notification resources for RemoteViews.
 *///w w w  . java 2  s  .  c o  m
private RemoteViews buildBaseNotification(final RemoteViews resultView) {
    final String title = mCurrentMusic.getTitle();

    /** If in streaming, the notification should be persistent. */
    if (app.getApplicationState().streamingMode && !StreamingService.isWoundDown()) {
        resultView.setViewVisibility(R.id.notificationClose, View.GONE);
    } else {
        resultView.setViewVisibility(R.id.notificationClose, View.VISIBLE);
        resultView.setOnClickPendingIntent(R.id.notificationClose, notificationClose);
    }

    if (MPDStatus.MPD_STATE_PLAYING.equals(getStatus().getState())) {
        resultView.setOnClickPendingIntent(R.id.notificationPlayPause, notificationPause);
        resultView.setImageViewResource(R.id.notificationPlayPause, R.drawable.ic_media_pause);
    } else {
        resultView.setOnClickPendingIntent(R.id.notificationPlayPause, notificationPlay);
        resultView.setImageViewResource(R.id.notificationPlayPause, R.drawable.ic_media_play);
    }

    /** When streaming, move things down (hopefully, very) temporarily. */
    if (mediaPlayerServiceIsBuffering) {
        resultView.setTextViewText(R.id.notificationTitle, getString(R.string.buffering));
        resultView.setTextViewText(R.id.notificationArtist, title);
    } else {
        resultView.setTextViewText(R.id.notificationTitle, title);
        resultView.setTextViewText(R.id.notificationArtist, mCurrentMusic.getArtist());
    }

    resultView.setOnClickPendingIntent(R.id.notificationNext, notificationNext);

    if (mAlbumCover != null) {
        resultView.setImageViewUri(R.id.notificationIcon, Uri.parse(mAlbumCoverPath));
    }

    return resultView;
}

From source file:com.eugene.fithealthmaingit.UI.NavFragments.FragmentJournalMainHome.java

/**
 * Equation for all of the Nutrition and Meal information
 *//*from www.j  a  va 2 s. c  o m*/
private void equations() {
    double mCalorieGoal = Double.valueOf(sharedPreferences.getString(Globals.USER_CALORIES_TO_REACH_GOAL, ""));
    double mFatGoal = Double.valueOf(sharedPreferences.getString(Globals.USER_DAILY_FAT, ""));
    double mCarbGoal = Double.valueOf(sharedPreferences.getString(Globals.USER_DAILY_CARBOHYDRATES, ""));
    double mProteinGoal = Double.valueOf(sharedPreferences.getString(Globals.USER_DAILY_PROTEIN, ""));
    mCalorieGoalMeal = Double.valueOf(sharedPreferences.getString(Globals.USER_CALORIES_TO_REACH_GOAL, "")) / 4;

    icSnack = (ImageView) v.findViewById(R.id.icSnack);
    icBreakfast = (ImageView) v.findViewById(R.id.icBreakfast);
    icLunch = (ImageView) v.findViewById(R.id.icLunch);
    icDinner = (ImageView) v.findViewById(R.id.icDinner);

    // _________________________Calories Snack_____________________________
    double mCalConsumedSnack = 0;
    for (LogMeal logMeal : mLogSnackAdapter.getLogs()) {
        mCalConsumedSnack += logMeal.getCalorieCount();
    }
    mCalSnack.setText(df.format(mCalConsumedSnack));

    // Set icon visible and color based on calories consumed for meal.
    if (mCalConsumedSnack >= mCalorieGoalMeal + 100) {
        icSnack.setImageResource(R.mipmap.ic_check_circle);
        icSnack.setColorFilter(Color.parseColor("#F44336"), android.graphics.PorterDuff.Mode.MULTIPLY);
    } else if (mCalConsumedSnack > mCalorieGoalMeal - 100 && mCalConsumedSnack < mCalorieGoalMeal + 99) {
        icSnack.setImageResource(R.mipmap.ic_check_circle);
        icSnack.setColorFilter(Color.parseColor("#4CAF50"), android.graphics.PorterDuff.Mode.MULTIPLY);
    } else {
        icSnack.setImageResource(R.mipmap.ic_check);
        icSnack.setColorFilter(Color.parseColor("#6D6D6D"), android.graphics.PorterDuff.Mode.MULTIPLY);
    }

    // _________________________Calories Breakfast_____________________________
    double mCalConsumedBreakfast = 0;
    for (LogMeal logMeal : mLogBreakfastAdapter.getLogs()) {
        mCalConsumedBreakfast += logMeal.getCalorieCount();
    }
    mCalBreakfast.setText(df.format(mCalConsumedBreakfast));

    // Set icon visible and color based on calories consumed for meal.
    if (mCalConsumedBreakfast >= mCalorieGoalMeal + 100) {
        icBreakfast.setColorFilter(Color.parseColor("#F44336"), android.graphics.PorterDuff.Mode.MULTIPLY);
        icBreakfast.setImageResource(R.mipmap.ic_check_circle);
    } else if (mCalConsumedBreakfast > mCalorieGoalMeal - 100
            && mCalConsumedBreakfast < mCalorieGoalMeal + 99) {
        icBreakfast.setColorFilter(Color.parseColor("#4CAF50"), android.graphics.PorterDuff.Mode.MULTIPLY);
        icBreakfast.setImageResource(R.mipmap.ic_check_circle);
    } else {
        icBreakfast.setImageResource(R.mipmap.ic_check);
        icBreakfast.setColorFilter(Color.parseColor("#6D6D6D"), android.graphics.PorterDuff.Mode.MULTIPLY);
    }

    // _________________________Calories Lunch_____________________________
    double mCalConsumedLunch = 0;
    for (LogMeal logMeal : mLogLunchAdapter.getLogs()) {
        mCalConsumedLunch += logMeal.getCalorieCount();
    }
    mCalLunch.setText(df.format(mCalConsumedLunch));

    // Set icon visible and color based on calories consumed for meal.
    if (mCalConsumedLunch >= mCalorieGoalMeal + 100) {
        icLunch.setImageResource(R.mipmap.ic_check_circle);
        icLunch.setColorFilter(Color.parseColor("#F44336"), android.graphics.PorterDuff.Mode.MULTIPLY);
    } else if (mCalConsumedLunch > mCalorieGoalMeal - 100 && mCalConsumedLunch < mCalorieGoalMeal + 99) {
        icLunch.setImageResource(R.mipmap.ic_check_circle);
        icLunch.setColorFilter(Color.parseColor("#4CAF50"), android.graphics.PorterDuff.Mode.MULTIPLY);
    } else {
        icLunch.setImageResource(R.mipmap.ic_check);
        icLunch.setColorFilter(Color.parseColor("#6D6D6D"), android.graphics.PorterDuff.Mode.MULTIPLY);
    }

    // _________________________Calories Lunch_____________________________
    double mCalConsumedDinner = 0;
    for (LogMeal logMeal : mLogDinnerAdapter.getLogs()) {
        mCalConsumedDinner += logMeal.getCalorieCount();
    }
    mCalDinner.setText(df.format(mCalConsumedDinner));

    // Set icon visible and color based on calories consumed for meal.
    if (mCalConsumedDinner >= mCalorieGoalMeal + 100) {
        icDinner.setImageResource(R.mipmap.ic_check_circle);
        icDinner.setColorFilter(Color.parseColor("#F44336"), android.graphics.PorterDuff.Mode.MULTIPLY);
    } else if (mCalConsumedDinner > mCalorieGoalMeal - 100 && mCalConsumedDinner < mCalorieGoalMeal + 99) {
        icDinner.setImageResource(R.mipmap.ic_check_circle);
        icDinner.setColorFilter(Color.parseColor("#4CAF50"), android.graphics.PorterDuff.Mode.MULTIPLY);
    } else {
        icDinner.setImageResource(R.mipmap.ic_check);
        icDinner.setColorFilter(Color.parseColor("#6D6D6D"), android.graphics.PorterDuff.Mode.MULTIPLY);
    }

    // _________________________Calories, Fat, Carbs, Protein All_____________________________
    // Nutrition Consumed
    double mAllCaloriesConsumed = 0;
    double mAllFatConsumed = 0;
    double mAllCarbsConsumed = 0;
    double mAllProteinConsumed = 0;

    for (LogMeal logMeal : mLogAdapterAll.getLogs()) {
        mAllCaloriesConsumed += logMeal.getCalorieCount();
        mAllFatConsumed += logMeal.getFatCount();
        mAllCarbsConsumed += logMeal.getCarbCount();
        mAllProteinConsumed += logMeal.getProteinCount();
    }
    // Nutrition Goals
    // Remainder Nutrition
    mCaloriesRemainder.setText(df.format(mCalorieGoal - mAllCaloriesConsumed) + " Left");
    mFatRemainder.setText(df.format(mFatGoal - mAllFatConsumed) + " Left");
    mCarbRemainder.setText(df.format(mCarbGoal - mAllCarbsConsumed) + " Left");
    mProteinRemainder.setText(df.format(mProteinGoal - mAllProteinConsumed) + " Left");
    // Progress bars

    mPbCalories.setMax(Integer.valueOf(df.format(mCalorieGoal)));
    mPbCalories.setProgress(Integer.valueOf(df.format(mAllCaloriesConsumed)));
    mPbFat.setMax(Integer.valueOf(df.format(mFatGoal)));
    mPbFat.setProgress(Integer.valueOf(df.format(mAllFatConsumed)));
    mPbCarbs.setMax(Integer.valueOf(df.format(mCarbGoal)));
    mPbCarbs.setProgress(Integer.valueOf(df.format(mAllCarbsConsumed)));
    mPbProtein.setMax(Integer.valueOf(df.format(mProteinGoal)));
    mPbProtein.setProgress(Integer.valueOf(df.format(mAllProteinConsumed)));

    /**
     * Update Widget
     */
    Context context = getActivity();
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
    if (appWidgetManager != null) {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.new_app_widget);
        ComponentName thisWidget = new ComponentName(context, FitHealthWidget.class);

        views.setProgressBar(R.id.pbCal, Integer.valueOf(df.format(mCalorieGoal)),
                Integer.valueOf(df.format(mAllCaloriesConsumed)), false);
        views.setProgressBar(R.id.pbFat, Integer.valueOf(df.format(mFatGoal)),
                Integer.valueOf(df.format(mAllFatConsumed)), false);
        views.setProgressBar(R.id.pbCarb, Integer.valueOf(df.format(mCarbGoal)),
                Integer.valueOf(df.format(mAllCarbsConsumed)), false);
        views.setProgressBar(R.id.pbPro, Integer.valueOf(df.format(mProteinGoal)),
                Integer.valueOf(df.format(mAllProteinConsumed)), false);

        views.setTextViewText(R.id.txtRemainderCal, df.format(mCalorieGoal - mAllCaloriesConsumed));
        views.setTextViewText(R.id.txtRemainderFat, df.format(mFatGoal - mAllFatConsumed));
        views.setTextViewText(R.id.txtRemainderCarb, df.format(mCarbGoal - mAllCarbsConsumed));
        views.setTextViewText(R.id.txtRemainderPro, df.format(mProteinGoal - mAllProteinConsumed));

        appWidgetManager.updateAppWidget(thisWidget, views);
    }
}

From source file:com.android.deskclock.data.StopwatchNotificationBuilderN.java

@Override
public Notification build(Context context, NotificationModel nm, Stopwatch stopwatch) {
    @StringRes/*w ww.j  a v  a2s.  co  m*/
    final int eventLabel = R.string.label_notification;

    // Intent to load the app when the notification is tapped.
    final Intent showApp = new Intent(context, HandleDeskClockApiCalls.class)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).setAction(HandleDeskClockApiCalls.ACTION_SHOW_STOPWATCH)
            .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

    final PendingIntent pendingShowApp = PendingIntent.getActivity(context, 0, showApp,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

    // Compute some values required below.
    final boolean running = stopwatch.isRunning();
    final String pname = context.getPackageName();
    final Resources res = context.getResources();
    final long base = SystemClock.elapsedRealtime() - stopwatch.getTotalTime();

    final RemoteViews content = new RemoteViews(pname, R.layout.chronometer_notif_content);
    content.setChronometer(R.id.chronometer, base, null, running);

    final List<Notification.Action> actions = new ArrayList<>(2);

    if (running) {
        // Left button: Pause
        final Intent pause = new Intent(context, StopwatchService.class)
                .setAction(HandleDeskClockApiCalls.ACTION_PAUSE_STOPWATCH)
                .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

        final Icon icon1 = Icon.createWithResource(context, R.drawable.ic_pause_24dp);
        final CharSequence title1 = res.getText(R.string.sw_pause_button);
        final PendingIntent intent1 = Utils.pendingServiceIntent(context, pause);
        actions.add(new Notification.Action.Builder(icon1, title1, intent1).build());

        // Right button: Add Lap
        if (DataModel.getDataModel().canAddMoreLaps()) {
            final Intent lap = new Intent(context, StopwatchService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_LAP_STOPWATCH)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

            final Icon icon2 = Icon.createWithResource(context, R.drawable.ic_sw_lap_24dp);
            final CharSequence title2 = res.getText(R.string.sw_lap_button);
            final PendingIntent intent2 = Utils.pendingServiceIntent(context, lap);
            actions.add(new Notification.Action.Builder(icon2, title2, intent2).build());
        }

        // Show the current lap number if any laps have been recorded.
        final int lapCount = DataModel.getDataModel().getLaps().size();
        if (lapCount > 0) {
            final int lapNumber = lapCount + 1;
            final String lap = res.getString(R.string.sw_notification_lap_number, lapNumber);
            content.setTextViewText(R.id.state, lap);
            content.setViewVisibility(R.id.state, VISIBLE);
        } else {
            content.setViewVisibility(R.id.state, GONE);
        }
    } else {
        // Left button: Start
        final Intent start = new Intent(context, StopwatchService.class)
                .setAction(HandleDeskClockApiCalls.ACTION_START_STOPWATCH)
                .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

        final Icon icon1 = Icon.createWithResource(context, R.drawable.ic_start_24dp);
        final CharSequence title1 = res.getText(R.string.sw_start_button);
        final PendingIntent intent1 = Utils.pendingServiceIntent(context, start);
        actions.add(new Notification.Action.Builder(icon1, title1, intent1).build());

        // Right button: Reset (dismisses notification and resets stopwatch)
        final Intent reset = new Intent(context, StopwatchService.class)
                .setAction(HandleDeskClockApiCalls.ACTION_RESET_STOPWATCH)
                .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

        final Icon icon2 = Icon.createWithResource(context, R.drawable.ic_reset_24dp);
        final CharSequence title2 = res.getText(R.string.sw_reset_button);
        final PendingIntent intent2 = Utils.pendingServiceIntent(context, reset);
        actions.add(new Notification.Action.Builder(icon2, title2, intent2).build());

        // Indicate the stopwatch is paused.
        content.setTextViewText(R.id.state, res.getString(R.string.swn_paused));
        content.setViewVisibility(R.id.state, VISIBLE);
    }

    // Swipe away will reset the stopwatch without bringing forward the app.
    final Intent reset = new Intent(context, StopwatchService.class)
            .setAction(HandleDeskClockApiCalls.ACTION_RESET_STOPWATCH)
            .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

    return new Notification.Builder(context).setLocalOnly(true).setOngoing(running)
            .setCustomContentView(content).setContentIntent(pendingShowApp).setAutoCancel(stopwatch.isPaused())
            .setPriority(Notification.PRIORITY_MAX).setSmallIcon(R.drawable.stat_notify_stopwatch)
            .setGroup(nm.getStopwatchNotificationGroupKey())
            .setStyle(new Notification.DecoratedCustomViewStyle())
            .setDeleteIntent(Utils.pendingServiceIntent(context, reset))
            .setActions(actions.toArray(new Notification.Action[actions.size()]))
            .setColor(ContextCompat.getColor(context, R.color.default_background)).build();
}

From source file:com.androidinspain.deskclock.data.StopwatchNotificationBuilder.java

public Notification build(Context context, NotificationModel nm, Stopwatch stopwatch) {
    @StringRes/*from   w w  w.  j a v  a 2  s.  c om*/
    final int eventLabel = com.androidinspain.deskclock.R.string.label_notification;

    // Intent to load the app when the notification is tapped.
    final Intent showApp = new Intent(context, StopwatchService.class)
            .setAction(StopwatchService.ACTION_SHOW_STOPWATCH).putExtra(Events.EXTRA_EVENT_LABEL, eventLabel);

    final PendingIntent pendingShowApp = PendingIntent.getService(context, 0, showApp,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

    // Compute some values required below.
    final boolean running = stopwatch.isRunning();
    final String pname = context.getPackageName();
    final Resources res = context.getResources();
    final long base = SystemClock.elapsedRealtime() - stopwatch.getTotalTime();

    final RemoteViews content = new RemoteViews(pname,
            com.androidinspain.deskclock.R.layout.chronometer_notif_content);
    content.setChronometer(com.androidinspain.deskclock.R.id.chronometer, base, null, running);

    final List<Action> actions = new ArrayList<>(2);

    if (running) {
        // Left button: Pause
        final Intent pause = new Intent(context, StopwatchService.class)
                .setAction(StopwatchService.ACTION_PAUSE_STOPWATCH)
                .putExtra(Events.EXTRA_EVENT_LABEL, eventLabel);

        @DrawableRes
        final int icon1 = com.androidinspain.deskclock.R.drawable.ic_pause_24dp;
        final CharSequence title1 = res.getText(com.androidinspain.deskclock.R.string.sw_pause_button);
        final PendingIntent intent1 = Utils.pendingServiceIntent(context, pause);
        actions.add(new Action.Builder(icon1, title1, intent1).build());

        // Right button: Add Lap
        if (DataModel.getDataModel().canAddMoreLaps()) {
            final Intent lap = new Intent(context, StopwatchService.class)
                    .setAction(StopwatchService.ACTION_LAP_STOPWATCH)
                    .putExtra(Events.EXTRA_EVENT_LABEL, eventLabel);

            @DrawableRes
            final int icon2 = com.androidinspain.deskclock.R.drawable.ic_sw_lap_24dp;
            final CharSequence title2 = res.getText(com.androidinspain.deskclock.R.string.sw_lap_button);
            final PendingIntent intent2 = Utils.pendingServiceIntent(context, lap);
            actions.add(new Action.Builder(icon2, title2, intent2).build());
        }

        // Show the current lap number if any laps have been recorded.
        final int lapCount = DataModel.getDataModel().getLaps().size();
        if (lapCount > 0) {
            final int lapNumber = lapCount + 1;
            final String lap = res.getString(com.androidinspain.deskclock.R.string.sw_notification_lap_number,
                    lapNumber);
            content.setTextViewText(com.androidinspain.deskclock.R.id.state, lap);
            content.setViewVisibility(com.androidinspain.deskclock.R.id.state, VISIBLE);
        } else {
            content.setViewVisibility(com.androidinspain.deskclock.R.id.state, GONE);
        }
    } else {
        // Left button: Start
        final Intent start = new Intent(context, StopwatchService.class)
                .setAction(StopwatchService.ACTION_START_STOPWATCH)
                .putExtra(Events.EXTRA_EVENT_LABEL, eventLabel);

        @DrawableRes
        final int icon1 = com.androidinspain.deskclock.R.drawable.ic_start_24dp;
        final CharSequence title1 = res.getText(com.androidinspain.deskclock.R.string.sw_start_button);
        final PendingIntent intent1 = Utils.pendingServiceIntent(context, start);
        actions.add(new Action.Builder(icon1, title1, intent1).build());

        // Right button: Reset (dismisses notification and resets stopwatch)
        final Intent reset = new Intent(context, StopwatchService.class)
                .setAction(StopwatchService.ACTION_RESET_STOPWATCH)
                .putExtra(Events.EXTRA_EVENT_LABEL, eventLabel);

        @DrawableRes
        final int icon2 = com.androidinspain.deskclock.R.drawable.ic_reset_24dp;
        final CharSequence title2 = res.getText(com.androidinspain.deskclock.R.string.sw_reset_button);
        final PendingIntent intent2 = Utils.pendingServiceIntent(context, reset);
        actions.add(new Action.Builder(icon2, title2, intent2).build());

        // Indicate the stopwatch is paused.
        content.setTextViewText(com.androidinspain.deskclock.R.id.state,
                res.getString(com.androidinspain.deskclock.R.string.swn_paused));
        content.setViewVisibility(com.androidinspain.deskclock.R.id.state, VISIBLE);
    }

    final Builder notification = new NotificationCompat.Builder(context).setLocalOnly(true).setOngoing(running)
            .setCustomContentView(content).setContentIntent(pendingShowApp).setAutoCancel(stopwatch.isPaused())
            .setPriority(Notification.PRIORITY_MAX)
            .setSmallIcon(com.androidinspain.deskclock.R.drawable.stat_notify_stopwatch)
            .setStyle(new NotificationCompat.DecoratedCustomViewStyle())
            .setColor(ContextCompat.getColor(context, com.androidinspain.deskclock.R.color.default_background));

    if (Utils.isNOrLater()) {
        notification.setGroup(nm.getStopwatchNotificationGroupKey());
    }

    for (Action action : actions) {
        notification.addAction(action);
    }

    return notification.build();
}

From source file:com.piusvelte.taplock.client.core.TapLockService.java

private void buildWidget(int appWidgetId) {
    RemoteViews rv = new RemoteViews(getPackageName(), R.layout.widget);
    String deviceName = null;// w ww. j  av a 2 s.  c  om
    for (JSONObject deviceJObj : mDevices) {
        if (deviceJObj.has(KEY_WIDGETS) && deviceJObj.has(KEY_NAME)) {
            JSONArray widgetsJArr = null;
            try {
                widgetsJArr = deviceJObj.getJSONArray(KEY_WIDGETS);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (widgetsJArr != null) {
                for (int i = 0, l = widgetsJArr.length(); (i < l) && (deviceName == null); i++) {
                    int widgetId;
                    try {
                        widgetId = widgetsJArr.getInt(i);
                    } catch (JSONException e) {
                        widgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
                        e.printStackTrace();
                    }
                    if ((widgetId != AppWidgetManager.INVALID_APPWIDGET_ID) && (appWidgetId == widgetId)) {
                        try {
                            deviceName = deviceJObj.getString(KEY_NAME);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        break;
                    }
                }
            }
            if (deviceName != null)
                break;
        }
    }
    if (deviceName == null)
        deviceName = "unknown";
    rv.setTextViewText(R.id.device_name, deviceName);
    rv.setOnClickPendingIntent(R.id.widget_icon,
            PendingIntent.getActivity(this, 0,
                    TapLock.getPackageIntent(this, TapLockToggle.class)
                            .setData(Uri.parse(String.format(getString(R.string.device_uri), deviceName))),
                    Intent.FLAG_ACTIVITY_NEW_TASK));
    AppWidgetManager.getInstance(this).updateAppWidget(appWidgetId, rv);
}

From source file:org.torproject.android.service.TorService.java

@SuppressLint("NewApi")
private void showToolbarNotification(String notifyMsg, int notifyType, int icon) {

    //Reusable code.
    Intent intent = new Intent(TorService.this, OrbotMainActivity.class);
    PendingIntent pendIntent = PendingIntent.getActivity(TorService.this, 0, intent, 0);

    if (mNotifyBuilder == null) {

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

        if (mNotifyBuilder == null) {
            mNotifyBuilder = new Notification.Builder(this).setContentTitle(getString(R.string.app_name))
                    .setSmallIcon(R.drawable.ic_stat_tor);

            mNotifyBuilder.setContentIntent(pendIntent);
        }//  www  .j av  a 2s .c o m

    }

    mNotifyBuilder.setContentText(notifyMsg);
    mNotifyBuilder.setSmallIcon(icon);

    if (notifyType != NOTIFY_ID) {
        mNotifyBuilder.setTicker(notifyMsg);
        //    mNotifyBuilder.setLights(Color.GREEN, 1000, 1000);
    } else {
        mNotifyBuilder.setTicker(null);
    }

    mNotifyBuilder.setOngoing(Prefs.persistNotifications());

    mNotification = mNotifyBuilder.build();

    if (Build.VERSION.SDK_INT >= 16 && Prefs.expandedNotifications()) {
        // Create remote view that needs to be set as bigContentView for the notification.
        RemoteViews expandedView = new RemoteViews(this.getPackageName(),
                R.layout.layout_notification_expanded);

        StringBuffer sbInfo = new StringBuffer();

        if (notifyType == NOTIFY_ID)
            expandedView.setTextViewText(R.id.text, notifyMsg);
        else {
            expandedView.setTextViewText(R.id.info, notifyMsg);
        }

        if (hmBuiltNodes.size() > 0) {
            Set<String> itBuiltNodes = hmBuiltNodes.keySet();
            for (String key : itBuiltNodes) {
                Node node = hmBuiltNodes.get(key);

                if (node.ipAddress != null) {
                    sbInfo.append(node.ipAddress);

                    if (node.country != null)
                        sbInfo.append(' ').append(node.country);

                    if (node.organization != null)
                        sbInfo.append(" (").append(node.organization).append(')');

                    sbInfo.append('\n');
                }

            }

            expandedView.setTextViewText(R.id.text2, sbInfo.toString());
        }

        expandedView.setTextViewText(R.id.title, getString(R.string.app_name));

        expandedView.setImageViewResource(R.id.icon, icon);
        mNotification.bigContentView = expandedView;
    }

    if (Prefs.persistNotifications() && (!mNotificationShowing)) {
        startForeground(NOTIFY_ID, mNotification);
        logNotice("Set background service to FOREGROUND");
    } else {
        mNotificationManager.notify(NOTIFY_ID, mNotification);
    }

    mNotificationShowing = true;
}

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

@Override
public Notification build(Context context, NotificationModel nm, Stopwatch stopwatch) {
    @StringRes/*from  www .j av a2 s .co m*/
    final int eventLabel = com.wizardsofm.deskclock.R.string.label_notification;

    // Intent to load the app when the notification is tapped.
    final Intent showApp = new Intent(context, HandleDeskClockApiCalls.class)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).setAction(HandleDeskClockApiCalls.ACTION_SHOW_STOPWATCH)
            .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

    final PendingIntent pendingShowApp = PendingIntent.getActivity(context, 0, showApp,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

    // Compute some values required below.
    final boolean running = stopwatch.isRunning();
    final String pname = context.getPackageName();
    final Resources res = context.getResources();
    final long base = SystemClock.elapsedRealtime() - stopwatch.getTotalTime();

    final RemoteViews content = new RemoteViews(pname,
            com.wizardsofm.deskclock.R.layout.chronometer_notif_content);
    content.setChronometer(com.wizardsofm.deskclock.R.id.chronometer, base, null, running);

    final List<Notification.Action> actions = new ArrayList<>(2);

    if (running) {
        // Left button: Pause
        final Intent pause = new Intent(context, StopwatchService.class)
                .setAction(HandleDeskClockApiCalls.ACTION_PAUSE_STOPWATCH)
                .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

        final Icon icon1 = Icon.createWithResource(context, com.wizardsofm.deskclock.R.drawable.ic_pause_24dp);
        final CharSequence title1 = res.getText(com.wizardsofm.deskclock.R.string.sw_pause_button);
        final PendingIntent intent1 = Utils.pendingServiceIntent(context, pause);
        actions.add(new Notification.Action.Builder(icon1, title1, intent1).build());

        // Right button: Add Lap
        if (DataModel.getDataModel().canAddMoreLaps()) {
            final Intent lap = new Intent(context, StopwatchService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_LAP_STOPWATCH)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

            final Icon icon2 = Icon.createWithResource(context,
                    com.wizardsofm.deskclock.R.drawable.ic_sw_lap_24dp);
            final CharSequence title2 = res.getText(com.wizardsofm.deskclock.R.string.sw_lap_button);
            final PendingIntent intent2 = Utils.pendingServiceIntent(context, lap);
            actions.add(new Notification.Action.Builder(icon2, title2, intent2).build());
        }

        // Show the current lap number if any laps have been recorded.
        final int lapCount = DataModel.getDataModel().getLaps().size();
        if (lapCount > 0) {
            final int lapNumber = lapCount + 1;
            final String lap = res.getString(com.wizardsofm.deskclock.R.string.sw_notification_lap_number,
                    lapNumber);
            content.setTextViewText(com.wizardsofm.deskclock.R.id.state, lap);
            content.setViewVisibility(com.wizardsofm.deskclock.R.id.state, VISIBLE);
        } else {
            content.setViewVisibility(com.wizardsofm.deskclock.R.id.state, GONE);
        }
    } else {
        // Left button: Start
        final Intent start = new Intent(context, StopwatchService.class)
                .setAction(HandleDeskClockApiCalls.ACTION_START_STOPWATCH)
                .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

        final Icon icon1 = Icon.createWithResource(context, com.wizardsofm.deskclock.R.drawable.ic_start_24dp);
        final CharSequence title1 = res.getText(com.wizardsofm.deskclock.R.string.sw_start_button);
        final PendingIntent intent1 = Utils.pendingServiceIntent(context, start);
        actions.add(new Notification.Action.Builder(icon1, title1, intent1).build());

        // Right button: Reset (dismisses notification and resets stopwatch)
        final Intent reset = new Intent(context, StopwatchService.class)
                .setAction(HandleDeskClockApiCalls.ACTION_RESET_STOPWATCH)
                .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

        final Icon icon2 = Icon.createWithResource(context, com.wizardsofm.deskclock.R.drawable.ic_reset_24dp);
        final CharSequence title2 = res.getText(com.wizardsofm.deskclock.R.string.sw_reset_button);
        final PendingIntent intent2 = Utils.pendingServiceIntent(context, reset);
        actions.add(new Notification.Action.Builder(icon2, title2, intent2).build());

        // Indicate the stopwatch is paused.
        content.setTextViewText(com.wizardsofm.deskclock.R.id.state,
                res.getString(com.wizardsofm.deskclock.R.string.swn_paused));
        content.setViewVisibility(com.wizardsofm.deskclock.R.id.state, VISIBLE);
    }

    // Swipe away will reset the stopwatch without bringing forward the app.
    final Intent reset = new Intent(context, StopwatchService.class)
            .setAction(HandleDeskClockApiCalls.ACTION_RESET_STOPWATCH)
            .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, eventLabel);

    return new Notification.Builder(context).setLocalOnly(true).setOngoing(running)
            .setCustomContentView(content).setContentIntent(pendingShowApp).setAutoCancel(stopwatch.isPaused())
            .setPriority(Notification.PRIORITY_MAX)
            .setSmallIcon(com.wizardsofm.deskclock.R.drawable.stat_notify_stopwatch)
            .setGroup(nm.getStopwatchNotificationGroupKey())
            .setStyle(new Notification.DecoratedCustomViewStyle())
            .setDeleteIntent(Utils.pendingServiceIntent(context, reset))
            .setActions(actions.toArray(new Notification.Action[actions.size()]))
            .setColor(ContextCompat.getColor(context, com.wizardsofm.deskclock.R.color.default_background))
            .build();
}

From source file:uk.org.ngo.squeezer.service.SqueezeService.java

/**
 * Manages the state of any ongoing notification based on the player and connection state.
 *//*  ww w.  ja v  a 2  s .  co m*/
private void updateOngoingNotification() {
    Player activePlayer = this.mActivePlayer.get();
    PlayerState activePlayerState = getActivePlayerState();

    // Update scrobble state, if either we're currently scrobbling, or we
    // were (to catch the case where we started scrobbling a song, and the
    // user went in to settings to disable scrobbling).
    if (scrobblingEnabled || scrobblingPreviouslyEnabled) {
        scrobblingPreviouslyEnabled = scrobblingEnabled;
        Scrobble.scrobbleFromPlayerState(this, activePlayerState);
    }

    // If there's no active player then kill the notification and get out.
    // TODO: Have a "There are no connected players" notification text.
    if (activePlayer == null || activePlayerState == null) {
        clearOngoingNotification();
        return;
    }

    boolean playing = activePlayerState.isPlaying();

    // If the song is not playing and the user wants notifications only when playing then
    // kill the notification and get out.
    if (!playing && !mShowNotificationWhenNotPlaying) {
        clearOngoingNotification();
        return;
    }

    // If there's no current song then kill the notification and get out.
    // TODO: Have a "There's nothing playing" notification text.
    final Song currentSong = activePlayerState.getCurrentSong();
    if (currentSong == null) {
        clearOngoingNotification();
        return;
    }

    // Compare the current state with the state when the notification was last updated.
    // If there are no changes (same song, same playing state) then there's nothing to do.
    String songName = currentSong.getName();
    String albumName = currentSong.getAlbumName();
    String artistName = currentSong.getArtist();
    Uri url = currentSong.getArtworkUrl();
    String playerName = activePlayer.getName();

    if (mNotifiedPlayerState == null) {
        mNotifiedPlayerState = new PlayerState();
    } else {
        boolean lastPlaying = mNotifiedPlayerState.isPlaying();
        Song lastNotifiedSong = mNotifiedPlayerState.getCurrentSong();

        // No change in state
        if (playing == lastPlaying && currentSong.equals(lastNotifiedSong)) {
            return;
        }
    }

    mNotifiedPlayerState.setCurrentSong(currentSong);
    mNotifiedPlayerState.setPlayStatus(activePlayerState.getPlayStatus());
    final NotificationManagerCompat nm = NotificationManagerCompat.from(this);

    PendingIntent nextPendingIntent = getPendingIntent(ACTION_NEXT_TRACK);
    PendingIntent prevPendingIntent = getPendingIntent(ACTION_PREV_TRACK);
    PendingIntent playPendingIntent = getPendingIntent(ACTION_PLAY);
    PendingIntent pausePendingIntent = getPendingIntent(ACTION_PAUSE);
    PendingIntent closePendingIntent = getPendingIntent(ACTION_CLOSE);

    Intent showNowPlaying = new Intent(this, NowPlayingActivity.class)
            .setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, showNowPlaying, 0);
    Notification notification;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        final Notification.Builder builder = new Notification.Builder(this);
        builder.setContentIntent(pIntent);
        builder.setSmallIcon(R.drawable.squeezer_notification);
        builder.setVisibility(Notification.VISIBILITY_PUBLIC);
        builder.setShowWhen(false);
        builder.setContentTitle(songName);
        builder.setContentText(albumName);
        builder.setSubText(playerName);
        builder.setStyle(new Notification.MediaStyle().setShowActionsInCompactView(1, 2)
                .setMediaSession(mMediaSession.getSessionToken()));

        final MediaMetadata.Builder metaBuilder = new MediaMetadata.Builder();
        metaBuilder.putString(MediaMetadata.METADATA_KEY_ARTIST, artistName);
        metaBuilder.putString(MediaMetadata.METADATA_KEY_ALBUM, albumName);
        metaBuilder.putString(MediaMetadata.METADATA_KEY_TITLE, songName);
        mMediaSession.setMetadata(metaBuilder.build());

        // Don't set an ongoing notification, otherwise wearable's won't show it.
        builder.setOngoing(false);

        builder.setDeleteIntent(closePendingIntent);
        if (playing) {
            builder.addAction(
                    new Notification.Action(R.drawable.ic_action_previous, "Previous", prevPendingIntent))
                    .addAction(new Notification.Action(R.drawable.ic_action_pause, "Pause", pausePendingIntent))
                    .addAction(new Notification.Action(R.drawable.ic_action_next, "Next", nextPendingIntent));
        } else {
            builder.addAction(
                    new Notification.Action(R.drawable.ic_action_previous, "Previous", prevPendingIntent))
                    .addAction(new Notification.Action(R.drawable.ic_action_play, "Play", playPendingIntent))
                    .addAction(new Notification.Action(R.drawable.ic_action_next, "Next", nextPendingIntent));
        }

        ImageFetcher.getInstance(this).loadImage(url,
                getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_width),
                getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_height),
                new ImageWorker.ImageWorkerCallback() {
                    @Override
                    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                    public void process(Object data, @Nullable Bitmap bitmap) {
                        if (bitmap == null) {
                            bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_album_noart);
                        }

                        metaBuilder.putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, bitmap);
                        metaBuilder.putBitmap(MediaMetadata.METADATA_KEY_ART, bitmap);
                        mMediaSession.setMetadata(metaBuilder.build());
                        builder.setLargeIcon(bitmap);
                        nm.notify(PLAYBACKSERVICE_STATUS, builder.build());
                    }
                });
    } else {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

        builder.setOngoing(true);
        builder.setCategory(NotificationCompat.CATEGORY_SERVICE);
        builder.setSmallIcon(R.drawable.squeezer_notification);

        RemoteViews normalView = new RemoteViews(this.getPackageName(), R.layout.notification_player_normal);
        RemoteViews expandedView = new RemoteViews(this.getPackageName(),
                R.layout.notification_player_expanded);

        normalView.setOnClickPendingIntent(R.id.next, nextPendingIntent);

        expandedView.setOnClickPendingIntent(R.id.previous, prevPendingIntent);
        expandedView.setOnClickPendingIntent(R.id.next, nextPendingIntent);

        builder.setContent(normalView);

        normalView.setTextViewText(R.id.trackname, songName);
        normalView.setTextViewText(R.id.albumname, albumName);

        expandedView.setTextViewText(R.id.trackname, songName);
        expandedView.setTextViewText(R.id.albumname, albumName);
        expandedView.setTextViewText(R.id.player_name, playerName);

        if (playing) {
            normalView.setImageViewResource(R.id.pause, R.drawable.ic_action_pause);
            normalView.setOnClickPendingIntent(R.id.pause, pausePendingIntent);

            expandedView.setImageViewResource(R.id.pause, R.drawable.ic_action_pause);
            expandedView.setOnClickPendingIntent(R.id.pause, pausePendingIntent);
        } else {
            normalView.setImageViewResource(R.id.pause, R.drawable.ic_action_play);
            normalView.setOnClickPendingIntent(R.id.pause, playPendingIntent);

            expandedView.setImageViewResource(R.id.pause, R.drawable.ic_action_play);
            expandedView.setOnClickPendingIntent(R.id.pause, playPendingIntent);
        }

        builder.setContentTitle(songName);
        builder.setContentText(getString(R.string.notification_playing_text, playerName));
        builder.setContentIntent(pIntent);

        notification = builder.build();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            notification.bigContentView = expandedView;
        }

        nm.notify(PLAYBACKSERVICE_STATUS, notification);

        ImageFetcher.getInstance(this).loadImage(this, url, normalView, R.id.album,
                getResources().getDimensionPixelSize(R.dimen.album_art_icon_normal_notification_width),
                getResources().getDimensionPixelSize(R.dimen.album_art_icon_normal_notification_height), nm,
                PLAYBACKSERVICE_STATUS, notification);
        ImageFetcher.getInstance(this).loadImage(this, url, expandedView, R.id.album,
                getResources().getDimensionPixelSize(R.dimen.album_art_icon_expanded_notification_width),
                getResources().getDimensionPixelSize(R.dimen.album_art_icon_expanded_notification_height), nm,
                PLAYBACKSERVICE_STATUS, notification);
    }
}

From source file:eu.trentorise.smartcampus.widget.shortcuts.StackWidgetService.java

@Override
public RemoteViews getViewAt(int position) {
    // position will always range from 0 to getCount() - 1.

    // We construct a remote views item based on our widget item xml
    // file, and set the
    // text based on the position.
    RemoteViews rv = new RemoteViews(mContext.getPackageName(), R.layout.widget_item);
    ShapeDrawable sd1 = new ShapeDrawable(new RectShape());
    sd1.getPaint().setColor(0xFFFFFFFF);
    sd1.getPaint().setStyle(Style.STROKE);
    sd1.getPaint().setStrokeWidth(1);/*w  w  w  .  j a  v a2s. c  o m*/
    Canvas c = new Canvas();
    sd1.draw(c);
    Bitmap b = Bitmap.createBitmap(120, 120, Bitmap.Config.ARGB_8888);
    c.drawBitmap(b, 0, 0, sd1.getPaint());
    // Next, we set a fill-intent which will be used to fill-in the
    // pending intent template
    // which is set on the collection view in StackWidgetProvider.

    if (ALLPREFERENCES != null && ALLPREFERENCES[position] != null) { //ALLPREFERENCES  dimensionato come le preferenze selezionate

        BookmarkDescriptor myDescriptor = ALLPREFERENCES[position];

        // set the widgetbutton
        if (WidgetHelper.PARAM_TYPE.equals(myDescriptor.params.get(0).name)) { //controllare con gli input da config activity?
            String type = myDescriptor.params.get(0).value;
            if (WidgetHelper.TYPE_DT.equals(type)) {
                // dt -> put icons and hide text
                rv.setViewVisibility(R.id.text_widget_item, View.GONE);
                rv.setImageViewResource(R.id.image_widget_item,
                        Integer.parseInt(myDescriptor.params.get(2).value));

                rv.setInt(R.id.image_widget_item, "setBackgroundResource", R.drawable.rounded_border_dt);

            } else if (WidgetHelper.TYPE_JP.equals(type)) {
                // jp -> put text and hide icon

                rv.setViewVisibility(R.id.image_widget_item, View.GONE);
                // rv.setImageViewBitmap(R.id.text_widget_item,
                // getBackground(Color.parseColor("#6EB046")));
                if (!("0".equals(myDescriptor.params.get(2).value))) {
                    //bus
                    rv.setTextViewTextSize(R.id.text_widget_item, TypedValue.COMPLEX_UNIT_DIP, 80);

                    rv.setTextViewText(R.id.text_widget_item, RoutesHelper.getShortNameByRouteIdAndAgencyID(
                            myDescriptor.params.get(4).value, myDescriptor.params.get(3).value)); //4,3
                    rv.setTextColor(R.id.text_widget_item, Integer.parseInt(myDescriptor.params.get(2).value));//rv.setInt(R.id.text_widget_item, "setBackgroundColor",
                    //Integer.parseInt(myDescriptor.params.get(2).value));
                    rv.setInt(R.id.text_widget_item, "setBackgroundResource", R.drawable.rounded_border_jp);

                } else {
                    //train
                    rv.setTextViewTextSize(R.id.text_widget_item, TypedValue.COMPLEX_UNIT_DIP, 12);
                    //controllo contesto getRouteDescriptor i vari parametri
                    rv.setTextViewText(R.id.text_widget_item,
                            mContext.getString(
                                    RoutesHelper.getRouteDescriptorByRouteId(myDescriptor.params.get(3).value,
                                            myDescriptor.params.get(4).value).getNameResource()));
                    rv.setTextColor(R.id.text_widget_item, Color.BLACK);//Int(R.id.text_widget_item, "setBackgroundColor",Color.BLACK);
                    rv.setInt(R.id.text_widget_item, "setBackgroundResource", R.drawable.rounded_border_jp);

                }

            } else if (WidgetHelper.TYPE_JP_PARKINGS.equals(type)) {
                // jp parcheggio -> put text and hide icon
                rv.setViewVisibility(R.id.text_widget_item, View.GONE);
                rv.setImageViewResource(R.id.image_widget_item,
                        Integer.parseInt(myDescriptor.params.get(2).value));
                rv.setInt(R.id.image_widget_item, "setBackgroundResource", R.drawable.rounded_border_jp);

            }
            BookmarkDescriptor bookmark = myDescriptor;
            Bundle extras = new Bundle();
            extras.putString(StackWidgetProvider.EXTRA_INTENT, bookmark.getIntent());
            if (bookmark.getParams() != null) {
                for (Param param : bookmark.getParams()) {
                    extras.putString(param.name, param.value);

                }

            }
            Intent fillInIntent = new Intent(bookmark.getIntent());
            fillInIntent.putExtras(extras);
            rv.setOnClickFillInIntent(R.id.layout, fillInIntent);
        }

    }
    // Return the remote views object.
    // AppWidgetManager manager = AppWidgetManager.getInstance(mContext);
    // manager.updateAppWidget(thisWidget, rv);
    return rv;
}