Example usage for android.app Notification VISIBILITY_PUBLIC

List of usage examples for android.app Notification VISIBILITY_PUBLIC

Introduction

In this page you can find the example usage for android.app Notification VISIBILITY_PUBLIC.

Prototype

int VISIBILITY_PUBLIC

To view the source code for android.app Notification VISIBILITY_PUBLIC.

Click Source Link

Document

Notification visibility: Show this notification in its entirety on all lockscreens.

Usage

From source file:com.cyanogenmod.settings.otgtoggle.UsbDeviceMonitorService.java

void updateNotification(boolean connected, int mode) {
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    if (!connected) {
        nm.cancel(OTG_NOTIFICATION_ID);//from w  w w  .j  a  v  a 2  s.  co  m
        return;
    }

    final Intent clickIntent = new Intent(this, OtgModeChooserActivity.class)
            .putExtra(OtgModeChooserActivity.EXTRA_CURRENT_MODE, getDetectionMode());
    final PendingIntent clickPi = PendingIntent.getActivity(this, 0, clickIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    final int titleResId;
    switch (mode) {
    case MODE_HEADSET:
        titleResId = R.string.connection_notification_title_headset;
        break;
    case MODE_OTG:
        titleResId = R.string.connection_notification_title_otg;
        break;
    default:
        titleResId = R.string.connection_notification_title_detect;
        break;
    }

    final Notification.Builder builder = new Notification.Builder(this)
            .setSmallIcon(R.drawable.ic_headset_notification).setLocalOnly(true).setOngoing(true).setWhen(0)
            .setDefaults(0).setShowWhen(false).setCategory(Notification.CATEGORY_SERVICE)
            .setVisibility(Notification.VISIBILITY_PUBLIC).setPriority(Notification.PRIORITY_MIN)
            .setColor(getResources().getColor(com.android.internal.R.color.system_notification_accent_color))
            .setContentTitle(getString(titleResId))
            .setContentText(getString(R.string.connection_notification_text)).setContentIntent(clickPi);

    nm.notify(OTG_NOTIFICATION_ID, builder.build());
}

From source file:com.example.android.wearable.wear.wearnotifications.handlers.BigTextIntentService.java

private NotificationCompat.Builder recreateBuilderWithBigTextStyle() {

    // Main steps for building a BIG_TEXT_STYLE notification (for more detailed comments on
    // building this notification, check StandaloneMainActivity.java)::
    //      0. Get your data
    //      1. Build the BIG_TEXT_STYLE
    //      2. Set up main Intent for notification
    //      3. Create additional Actions for the Notification
    //      4. Build and issue the notification

    // 0. Get your data (everything unique per Notification)
    MockDatabase.BigTextStyleReminderAppData bigTextStyleReminderAppData = MockDatabase.getBigTextStyleData();

    // 1. Build the BIG_TEXT_STYLE
    BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle()
            .bigText(bigTextStyleReminderAppData.getBigText())
            .setBigContentTitle(bigTextStyleReminderAppData.getBigContentTitle())
            .setSummaryText(bigTextStyleReminderAppData.getSummaryText());

    // 2. Set up main Intent for notification
    Intent mainIntent = new Intent(this, BigTextMainActivity.class);

    PendingIntent mainPendingIntent = PendingIntent.getActivity(this, 0, mainIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // 3. Create additional Actions (Intents) for the Notification
    // Snooze Action
    Intent snoozeIntent = new Intent(this, BigTextIntentService.class);
    snoozeIntent.setAction(BigTextIntentService.ACTION_SNOOZE);

    PendingIntent snoozePendingIntent = PendingIntent.getService(this, 0, snoozeIntent, 0);
    NotificationCompat.Action snoozeAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_alarm_white_48dp, "Snooze", snoozePendingIntent).build();

    // Dismiss Action
    Intent dismissIntent = new Intent(this, BigTextIntentService.class);
    dismissIntent.setAction(BigTextIntentService.ACTION_DISMISS);

    PendingIntent dismissPendingIntent = PendingIntent.getService(this, 0, dismissIntent, 0);
    NotificationCompat.Action dismissAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_cancel_white_48dp, "Dismiss", dismissPendingIntent).build();

    // 4. Build and issue the notification
    NotificationCompat.Builder notificationCompatBuilder = new NotificationCompat.Builder(
            getApplicationContext());/*from   w  ww .  jav  a  2  s  .  c  o  m*/

    GlobalNotificationBuilder.setNotificationCompatBuilderInstance(notificationCompatBuilder);

    notificationCompatBuilder.setStyle(bigTextStyle)
            .setContentTitle(bigTextStyleReminderAppData.getContentTitle())
            .setContentText(bigTextStyleReminderAppData.getContentText()).setSmallIcon(R.drawable.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_alarm_white_48dp))
            .setColor(getResources().getColor(R.color.colorPrimary)).setCategory(Notification.CATEGORY_REMINDER)
            .setPriority(Notification.PRIORITY_HIGH).setVisibility(Notification.VISIBILITY_PUBLIC)
            .addAction(snoozeAction).addAction(dismissAction);

    /* REPLICATE_NOTIFICATION_STYLE_CODE:
     * You can replicate Notification Style functionality on Wear 2.0 (24+) by not setting the
     * main content intent, that is, skipping the call setContentIntent(). However, you need to
     * still allow the user to open the native Wear app from the Notification itself, so you
     * add an action to launch the app.
     */
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

        // Enables launching app in Wear 2.0 while keeping the old Notification Style behavior.
        NotificationCompat.Action mainAction = new NotificationCompat.Action.Builder(R.drawable.ic_launcher,
                "Open", mainPendingIntent).build();

        notificationCompatBuilder.addAction(mainAction);

    } else {
        // Wear 1.+ still functions the same, so we set the main content intent.
        notificationCompatBuilder.setContentIntent(mainPendingIntent);
    }

    return notificationCompatBuilder;
}

From source file:hmatalonga.greenhub.util.Notifier.java

public static void batteryHighTemperature(final Context context) {
    if (sNotificationManager == null) {
        sNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    }//from   w w w. j  a v a 2s. c o  m

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_alert_circle_white_24dp).setContentTitle("Battery temperature is hot!")
            .setContentText("Cool-down your phone for a while").setAutoCancel(true).setOngoing(false)
            .setLights(Color.RED, 500, 2000).setVibrate(new long[] { 0, 800, 1500 })
            .setPriority(SettingsUtils.fetchNotificationsPriority(context));

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

    // Because the ID remains unchanged, the existing notification is updated.
    Notification notification = mBuilder.build();
    notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE;
    sNotificationManager.notify(Config.NOTIFICATION_TEMPERATURE_HIGH, notification);
}

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

@Override
public Notification build(Context context, NotificationModel nm, List<Timer> unexpired) {
    final Timer timer = unexpired.get(0);
    final int count = unexpired.size();

    // Compute some values required below.
    final boolean running = timer.isRunning();
    final Resources res = context.getResources();

    final long base = getChronometerBase(timer);
    final String pname = context.getPackageName();
    final RemoteViews content = new RemoteViews(pname,
            com.wizardsofm.deskclock.R.layout.chronometer_notif_content);
    content.setChronometerCountDown(com.wizardsofm.deskclock.R.id.chronometer, true);
    content.setChronometer(com.wizardsofm.deskclock.R.id.chronometer, base, null, running);

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

    final CharSequence stateText;
    if (count == 1) {
        if (running) {
            // Single timer is running.
            if (TextUtils.isEmpty(timer.getLabel())) {
                stateText = res.getString(com.wizardsofm.deskclock.R.string.timer_notification_label);
            } else {
                stateText = timer.getLabel();
            }/* w  ww.ja v a  2 s  .  c om*/

            // Left button: Pause
            final Intent pause = new Intent(context, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_PAUSE_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());

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

            // Right Button: +1 Minute
            final Intent addMinute = new Intent(context, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_ADD_MINUTE_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());

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

        } else {
            // Single timer is paused.
            stateText = res.getString(com.wizardsofm.deskclock.R.string.timer_paused);

            // Left button: Start
            final Intent start = new Intent(context, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_START_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());

            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_resume_button);
            final PendingIntent intent1 = Utils.pendingServiceIntent(context, start);
            actions.add(new Notification.Action.Builder(icon1, title1, intent1).build());

            // Right Button: Reset
            final Intent reset = new Intent(context, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_RESET_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());

            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());
        }
    } else {
        if (running) {
            // At least one timer is running.
            stateText = res.getString(com.wizardsofm.deskclock.R.string.timers_in_use, count);
        } else {
            // All timers are paused.
            stateText = res.getString(com.wizardsofm.deskclock.R.string.timers_stopped, count);
        }

        final Intent reset = TimerService.createResetUnexpiredTimersIntent(context);

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

    content.setTextViewText(com.wizardsofm.deskclock.R.id.state, stateText);

    // Intent to load the app and show the timer when the notification is tapped.
    final Intent showApp = new Intent(context, HandleDeskClockApiCalls.class)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).setAction(HandleDeskClockApiCalls.ACTION_SHOW_TIMERS)
            .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId())
            .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL,
                    com.wizardsofm.deskclock.R.string.label_notification);

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

    return new Notification.Builder(context).setOngoing(true).setLocalOnly(true).setShowWhen(false)
            .setAutoCancel(false).setCustomContentView(content).setContentIntent(pendingShowApp)
            .setPriority(Notification.PRIORITY_HIGH).setCategory(Notification.CATEGORY_ALARM)
            .setSmallIcon(com.wizardsofm.deskclock.R.drawable.stat_notify_timer)
            .setGroup(nm.getTimerNotificationGroupKey()).setVisibility(Notification.VISIBILITY_PUBLIC)
            .setStyle(new Notification.DecoratedCustomViewStyle())
            .setActions(actions.toArray(new Notification.Action[actions.size()]))
            .setColor(ContextCompat.getColor(context, com.wizardsofm.deskclock.R.color.default_background))
            .build();
}

From source file:com.farmerbb.secondscreen.service.NotificationService.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override/* w ww  .j av  a2s . co  m*/
public void onCreate() {
    // Load preferences
    SharedPreferences prefCurrent = U.getPrefCurrent(this);
    SharedPreferences prefMain = U.getPrefMain(this);

    // Register broadcast receivers for screen on and user present
    final IntentFilter filter1 = new IntentFilter();
    final IntentFilter filter2 = new IntentFilter();

    filter1.addAction(Intent.ACTION_SCREEN_ON);
    filter1.addAction(Intent.ACTION_DREAMING_STARTED);
    filter2.addAction(Intent.ACTION_USER_PRESENT);

    registerReceiver(screenOnReceiver, filter1);
    registerReceiver(userPresentReceiver, filter2);

    DisplayManager manager = (DisplayManager) getSystemService(DISPLAY_SERVICE);
    manager.registerDisplayListener(listener, null);

    // Intent to launch MainActivity when notification is clicked
    Intent mainActivityIntent = new Intent(this, MainActivity.class);
    PendingIntent mainActivityPendingIntent = PendingIntent.getActivity(this, 0, mainActivityIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Build the notification
    mBuilder = new NotificationCompat.Builder(this).setContentIntent(mainActivityPendingIntent)
            .setSmallIcon(R.drawable.ic_action_dock)
            .setContentTitle(getResources().getString(R.string.notification))
            .setContentText(
                    prefCurrent.getString("profile_name", getResources().getString(R.string.action_new)))
            .setOngoing(true);

    // Set action buttons
    setActionButton(prefMain.getString("notification_action_2", "turn-off"), prefCurrent, 0);
    setActionButton(prefMain.getString("notification_action", "lock-device"), prefCurrent, 1);

    // Respect setting to hide notification
    if (prefMain.getBoolean("hide_notification", false))
        mBuilder.setPriority(Notification.PRIORITY_MIN);

    // Set notification color on Lollipop
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mBuilder.setColor(getResources().getColor(R.color.primary_dark))
                .setVisibility(Notification.VISIBILITY_PUBLIC);
    }

    // Start NotificationService
    startForeground(1, mBuilder.build());

    // Draw system overlay, if needed
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Settings.canDrawOverlays(this)
            && prefCurrent.getString("rotation_lock_new", "fallback").equals("landscape")) {
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);

        params.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;

        view = new View(this);
        windowManager.addView(view, params);
    }
}

From source file:info.tongrenlu.MediaNotificationManager.java

private Notification createNotification() {

    TrackBean playingTrack = mService.getPlaying();

    long action = mPlaybackState.getActions();
    boolean canPrev = (action & PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) != 0;
    boolean canNext = (action & PlaybackStateCompat.ACTION_SKIP_TO_NEXT) != 0;
    boolean isPlaying = mPlaybackState.getState() == PlaybackStateCompat.STATE_PLAYING;

    Bitmap art = BitmapFactory.decodeResource(mService.getResources(), R.drawable.ic_default_art);

    final String artUrl = "http://files.tongrenlu.info/m" + playingTrack.getArticleId() + "/cover_400.jpg";
    //        RequestCreator picasso = Picasso.with(mService.getApplicationContext())
    //                                        .load(artUrl)
    //                                        .placeholder(R.drawable.ic_default_art)
    //                                        .resizeDimen(android.R.dimen.notification_large_icon_width,
    //                                                     android.R.dimen.notification_large_icon_height)
    //                                        .centerCrop();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        final Notification.Builder builder = new Notification.Builder(mService);
        int playPauseButtonPosition = 0;

        if (canPrev) {
            builder.addAction(R.drawable.ic_skip_previous_white_24dp,
                    mService.getString(R.string.label_previous), mPreviousPendingIntent);
            playPauseButtonPosition = 1;
        }//w w w .  j  a va2s  .  c  om

        if (isPlaying) {
            builder.addAction(R.drawable.ic_pause_white_24dp, mService.getString(R.string.label_pause),
                    mTogglePlaybackPendingIntent);
        } else {
            builder.addAction(R.drawable.ic_play_arrow_white_24dp, mService.getString(R.string.label_play),
                    mTogglePlaybackPendingIntent);
        }

        if (canNext) {
            builder.addAction(R.drawable.ic_skip_next_white_24dp, mService.getString(R.string.label_next),
                    mNextPendingIntent);
        }

        builder.setDeleteIntent(mDeletePendingIntent);

        Notification.MediaStyle style = new Notification.MediaStyle();
        style.setShowActionsInCompactView(playPauseButtonPosition);

        builder.setStyle(style).setColor(mNotificationColor).setSmallIcon(R.drawable.ic_notification)
                .setVisibility(Notification.VISIBILITY_PUBLIC).setContentIntent(createContentIntent())
                .setContentTitle(playingTrack.getName()).setContentText(playingTrack.getAlbum())
                .setLargeIcon(art).setOngoing(isPlaying).setAutoCancel(false);

        if (mPlaybackState == null || !mStarted) {
            Log.d(TAG, "updateNotificationPlaybackState. cancelling notification!");
            mService.stopForeground(true);
        } else {
            if (isPlaying && mPlaybackState.getPosition() >= 0) {
                builder.setWhen(System.currentTimeMillis() - mPlaybackState.getPosition());
                builder.setShowWhen(true);
                builder.setUsesChronometer(true);
            } else {
                builder.setWhen(0);
                builder.setShowWhen(false);
                builder.setUsesChronometer(false);
            }
        }
        //
        //            picasso.into(new Target() {
        //                @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        //                @Override
        //                public void onBitmapLoaded(final Bitmap bitmap, final Picasso.LoadedFrom from) {
        //                    Log.d(TAG, "fetchBitmapFromURLAsync: set bitmap to " + artUrl);
        //                    builder.setLargeIcon(bitmap);
        //                    mNotificationManager.notify(NOTIFICATION_ID, builder.build());
        //                }
        //
        //                @Override
        //                public void onBitmapFailed(final Drawable errorDrawable) {
        //
        //                }
        //
        //                @Override
        //                public void onPrepareLoad(final Drawable placeHolderDrawable) {
        //
        //                }
        //            });
        return builder.build();
    } else {
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(mService);
        if (canPrev) {
            builder.addAction(R.drawable.ic_skip_previous_white_24dp,
                    mService.getString(R.string.label_previous), mPreviousPendingIntent);
        }

        if (isPlaying) {
            builder.addAction(R.drawable.ic_pause_white_24dp, mService.getString(R.string.label_pause),
                    mTogglePlaybackPendingIntent);
        } else {
            builder.addAction(R.drawable.ic_play_arrow_white_24dp, mService.getString(R.string.label_play),
                    mTogglePlaybackPendingIntent);
        }

        if (canNext) {
            builder.addAction(R.drawable.ic_skip_next_white_24dp, mService.getString(R.string.label_next),
                    mNextPendingIntent);
        }
        builder.setDeleteIntent(mDeletePendingIntent);

        builder.setColor(mNotificationColor).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setSmallIcon(R.drawable.ic_notification).setContentIntent(createContentIntent())
                .setContentTitle(playingTrack.getName()).setContentText(playingTrack.getAlbum())
                .setLargeIcon(art).setOngoing(isPlaying).setAutoCancel(false);

        if (mPlaybackState == null || !mStarted) {
            mService.stopForeground(true);
        } else {
            if (isPlaying && mPlaybackState.getPosition() >= 0) {
                builder.setWhen(System.currentTimeMillis() - mPlaybackState.getPosition());
                builder.setShowWhen(true);
                builder.setUsesChronometer(true);
            } else {
                builder.setWhen(0);
                builder.setShowWhen(false);
                builder.setUsesChronometer(false);
            }

        }
        //
        //            picasso.into(new Target() {
        //                @Override
        //                public void onBitmapLoaded(final Bitmap bitmap, final Picasso.LoadedFrom from) {
        //                    Log.d(TAG, "fetchBitmapFromURLAsync: set bitmap to " + artUrl);
        //                    builder.setLargeIcon(bitmap);
        //                    mNotificationManager.notify(NOTIFICATION_ID, builder.build());
        //                }
        //
        //                @Override
        //                public void onBitmapFailed(final Drawable errorDrawable) {
        //
        //                }
        //
        //                @Override
        //                public void onPrepareLoad(final Drawable placeHolderDrawable) {
        //
        //                }
        //            });
        return builder.build();
    }
}

From source file:com.devbrackets.android.exomedia.EMNotification.java

/**
 * Returns a fully constructed notification to use when moving a service to the
 * foreground.  This should be called after the notification information is set with
 * {@link #setNotificationBaseInformation(int, int)} and {@link #updateNotificationInformation(String, String, String, Bitmap, Bitmap)}.
 *
 * @param pendingIntent The pending intent to use when the notification itself is clicked
 * @return The constructed notification/*  w  ww . jav  a 2  s.  co m*/
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public Notification getNotification(@Nullable PendingIntent pendingIntent) {
    setClickPendingIntent(pendingIntent);
    RemoteViews customNotificationViews = getCustomNotification();

    boolean allowSwipe = notificationInfo.getMediaState() == null
            || !notificationInfo.getMediaState().isPlaying();

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setContent(customNotificationViews);
    builder.setContentIntent(pendingIntent);
    builder.setDeleteIntent(createPendingIntent(EMRemoteActions.ACTION_STOP, mediaServiceClass));
    builder.setSmallIcon(notificationInfo.getAppIcon());
    builder.setAutoCancel(allowSwipe);
    builder.setOngoing(!allowSwipe);

    if (pendingIntent != null) {
        customNotificationViews.setOnClickPendingIntent(R.id.exomedia_notification_touch_area, pendingIntent);
    }

    //Set the notification category on lollipop
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setCategory(Notification.CATEGORY_STATUS);
        builder.setVisibility(Notification.VISIBILITY_PUBLIC);
    }

    //Build the notification and set the expanded content view if there is a service to inform of clicks
    Notification notification = builder.build();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && mediaServiceClass != null) {
        notification.bigContentView = getBigNotification();
        notification.bigContentView.setOnClickPendingIntent(R.id.exomedia_big_notification_touch_area,
                pendingIntent);
    }

    return notification;
}

From source file:net.olejon.spotcommander.WebViewActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Google API client
    mGoogleApiClient = new GoogleApiClient.Builder(mContext).addApiIfAvailable(Wearable.API).build();

    // Allow landscape?
    if (!mTools.allowLandscape())
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    // Hide status bar?
    if (mTools.getDefaultSharedPreferencesBoolean("HIDE_STATUS_BAR"))
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

    // Power manager
    final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

    //noinspection deprecation
    mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "wakeLock");

    // Settings//from   w ww  .  ja  va 2s  .c om
    mTools.setSharedPreferencesBoolean("CAN_CLOSE_COVER", false);

    // Current network
    mCurrentNetwork = mTools.getCurrentNetwork();

    // Computer
    final long computerId = mTools.getSharedPreferencesLong("LAST_COMPUTER_ID");

    final String[] computer = mTools.getComputer(computerId);

    final String uri = computer[0];
    final String username = computer[1];
    final String password = computer[2];

    // Layout
    setContentView(R.layout.activity_webview);

    // Status bar color
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mStatusBarPrimaryColor = getWindow().getStatusBarColor();
        mStatusBarCoverArtColor = mStatusBarPrimaryColor;
    }

    // Notification
    mPersistentNotificationIsSupported = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN);

    if (mPersistentNotificationIsSupported) {
        final Intent launchActivityIntent = new Intent(mContext, MainActivity.class);
        launchActivityIntent.setAction("android.intent.action.MAIN");
        launchActivityIntent.addCategory("android.intent.category.LAUNCHER");
        mLaunchActivityPendingIntent = PendingIntent.getActivity(mContext, 0, launchActivityIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent hideIntent = new Intent(mContext, RemoteControlIntentService.class);
        hideIntent.setAction("hide_notification");
        hideIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mHidePendingIntent = PendingIntent.getService(mContext, 0, hideIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent previousIntent = new Intent(mContext, RemoteControlIntentService.class);
        previousIntent.setAction("previous");
        previousIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mPreviousPendingIntent = PendingIntent.getService(mContext, 0, previousIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent playPauseIntent = new Intent(mContext, RemoteControlIntentService.class);
        playPauseIntent.setAction("play_pause");
        playPauseIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mPlayPausePendingIntent = PendingIntent.getService(mContext, 0, playPauseIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent nextIntent = new Intent(mContext, RemoteControlIntentService.class);
        nextIntent.setAction("next");
        nextIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mNextPendingIntent = PendingIntent.getService(mContext, 0, nextIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent volumeDownIntent = new Intent(mContext, RemoteControlIntentService.class);
        volumeDownIntent.setAction("adjust_spotify_volume_down");
        volumeDownIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mVolumeDownPendingIntent = PendingIntent.getService(mContext, 0, volumeDownIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent volumeUpIntent = new Intent(mContext, RemoteControlIntentService.class);
        volumeUpIntent.setAction("adjust_spotify_volume_up");
        volumeUpIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mVolumeUpPendingIntent = PendingIntent.getService(mContext, 0, volumeUpIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        mNotificationManager = NotificationManagerCompat.from(mContext);
        mNotificationBuilder = new NotificationCompat.Builder(mContext);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
            mNotificationBuilder.setPriority(Notification.PRIORITY_MAX);

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

    // Web view
    mWebView = (WebView) findViewById(R.id.webview_webview);

    mWebView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.background));
    mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);

    mWebView.setWebViewClient(new WebViewClient() {
        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && !url.contains(uri)
                    && !url.contains("olejon.net/code/spotcommander/api/1/spotify/")
                    && !url.contains("accounts.spotify.com/") && !url.contains("facebook.com/")) {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));

                return true;
            }

            return false;
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view, @NonNull HttpAuthHandler handler, String host,
                String realm) {
            if (handler.useHttpAuthUsernamePassword()) {
                handler.proceed(username, password);
            } else {
                handler.cancel();

                mWebView.stopLoading();

                mTools.showToast(getString(R.string.webview_authentication_failed), 1);

                mTools.navigateUp(mActivity);
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest webResourceRequest,
                WebResourceError webResourceError) {
            mWebView.stopLoading();

            mTools.showToast(getString(R.string.webview_error), 1);

            mTools.navigateUp(mActivity);
        }

        @Override
        public void onReceivedSslError(WebView view, @NonNull SslErrorHandler handler, SslError error) {
            handler.cancel();

            mWebView.stopLoading();

            new MaterialDialog.Builder(mContext).title(R.string.webview_dialog_ssl_error_title)
                    .content(getString(R.string.webview_dialog_ssl_error_message))
                    .positiveText(R.string.webview_dialog_ssl_error_positive_button)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog materialDialog,
                                @NonNull DialogAction dialogAction) {
                            finish();
                        }
                    }).contentColorRes(R.color.black).show();
        }
    });

    // User agent
    mProjectVersionName = mTools.getProjectVersionName();

    final String uaAppend1 = (!username.equals("") && !password.equals("")) ? "AUTHENTICATION_ENABLED " : "";
    final String uaAppend2 = (mTools.getSharedPreferencesBoolean("WEAR_CONNECTED")) ? "WEAR_CONNECTED " : "";
    final String uaAppend3 = (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT
            && !mTools.getDefaultSharedPreferencesBoolean("HARDWARE_ACCELERATED_ANIMATIONS"))
                    ? "DISABLE_CSSTRANSITIONS DISABLE_CSSTRANSFORMS3D "
                    : "";

    // Web settings
    final WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setSupportZoom(false);
    webSettings.setUserAgentString(getString(R.string.webview_user_agent, webSettings.getUserAgentString(),
            mProjectVersionName, uaAppend1, uaAppend2, uaAppend3));

    // Load app
    if (savedInstanceState != null) {
        mWebView.restoreState(savedInstanceState);
    } else {
        mWebView.loadUrl(uri);
    }

    // JavaScript interface
    mWebView.addJavascriptInterface(new JavaScriptInterface(), "Android");
}

From source file:com.hmatalonga.greenhub.util.Notifier.java

public static void batteryLowAlert(final Context context) {
    if (sNotificationManager == null) {
        sNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    }//  w  w  w .ja v a2s. c o  m

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_alert_circle_white_24dp)
            .setContentTitle(context.getString(R.string.notif_battery_low))
            .setContentText(context.getString(R.string.notif_connect_power)).setAutoCancel(true)
            .setOngoing(false).setLights(Color.RED, 500, 2000).setVibrate(new long[] { 0, 400, 1000 })
            .setPriority(SettingsUtils.fetchNotificationsPriority(context));

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

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, MainActivity.class);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(InboxActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);

    // Because the ID remains unchanged, the existing notification is updated.
    sNotificationManager.notify(Config.NOTIFICATION_BATTERY_LOW, mBuilder.build());
}

From source file:com.devbrackets.android.playlistcore.helper.NotificationHelper.java

/**
 * Returns a fully constructed notification to use when moving a service to the
 * foreground.  This should be called after the notification information is set with
 * {@link #setNotificationBaseInformation(int, int)} and {@link #updateNotificationInformation(String, String, String, Bitmap, Bitmap)}.
 *
 * @param pendingIntent The pending intent to use when the notification itself is clicked
 * @return The constructed notification//from   w w w  .java2 s . c o m
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public Notification getNotification(@Nullable PendingIntent pendingIntent,
        @NonNull Class<? extends Service> serviceClass) {
    setClickPendingIntent(pendingIntent);
    RemoteViews customNotificationViews = getCustomNotification(serviceClass);

    boolean allowSwipe = notificationInfo.getMediaState() == null
            || !notificationInfo.getMediaState().isPlaying();

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setContent(customNotificationViews);
    builder.setContentIntent(pendingIntent);
    builder.setDeleteIntent(createPendingIntent(RemoteActions.ACTION_STOP, serviceClass));
    builder.setSmallIcon(notificationInfo.getAppIcon());
    builder.setAutoCancel(allowSwipe);
    builder.setOngoing(!allowSwipe);

    if (pendingIntent != null) {
        customNotificationViews.setOnClickPendingIntent(R.id.playlistcore_notification_touch_area,
                pendingIntent);
    }

    //Set the notification category on lollipop
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setCategory(Notification.CATEGORY_STATUS);
        builder.setVisibility(Notification.VISIBILITY_PUBLIC);
    }

    //Build the notification and set the expanded content view if there is a service to inform of clicks
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN && mediaServiceClass != null) {
        RemoteViews bigNotificationView = getBigNotification(serviceClass);
        bigNotificationView.setOnClickPendingIntent(R.id.playlistcore_big_notification_touch_area,
                pendingIntent);
        builder.setCustomBigContentView(bigNotificationView);
    }

    return builder.build();
}