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.example.kyle.weatherforecast.MainActivity.java

private void postAlert(int i) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentTitle("Weather Alert!").setContentText(WeatherData.outlookArray[i])
            .setSmallIcon(R.drawable.small_icon)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), WeatherData.symbolArray[i]))
            .setAutoCancel(true).setTicker("Wrap up warm!")
            // Heads-up and lock screen notifications
            .setVisibility(Notification.VISIBILITY_PUBLIC).setPriority(Notification.PRIORITY_HIGH)
            .setVibrate(new long[] { 100, 100, 100, 200, 200 }).setVibrate(new long[] { 0 })
            .setCategory(Notification.CATEGORY_ALARM);

    NotificationCompat.BigPictureStyle bigStyle = new NotificationCompat.BigPictureStyle();
    bigStyle.bigPicture(BitmapFactory.decodeResource(getResources(), R.drawable.snow_scene));
    builder.setStyle(bigStyle);// w  w w .  jav  a 2  s . c om

    Intent intent = new Intent(this, MainActivity.class);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class).addNextIntent(intent);
    PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) this
            .getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(notificationId, builder.build());

    notificationId++;
    Log.d(DEBUG_TAG, "ID: " + notificationId);
}

From source file:com.app.encontreibvrr.service.MyFirebaseMessagingService.java

/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 *///from   ww w.  ja  v a 2 s  .c  o  m
private void sendNotification(String messageBody) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    //Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher).setPriority(Notification.PRIORITY_MAX)
            .setDefaults(Notification.DEFAULT_ALL).setVisibility(Notification.VISIBILITY_PUBLIC)
            .setContentTitle("Encontrei BV RR").setContentText(messageBody).setAutoCancel(true)
            .setSound(defaultSoundUri).setContentIntent(pendingIntent);

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

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

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

public static void updateStatusBar(final Context context) {
    // In case status bar is not started yet call start method
    if (!isStatusBarShown) {
        startStatusBar(context);//from w w  w  . ja v a  2  s  .c o  m
        return;
    }

    int now = Battery.getBatteryCurrentNow(context);
    int level = (int) (Inspector.getCurrentBatteryLevel() * 100);
    String title = "Now: " + now + " mA";
    String text = "GreenHub is running";

    sBuilder.setContentTitle(title).setContentText(text).setAutoCancel(false).setOngoing(true)
            .setPriority(SettingsUtils.fetchNotificationsPriority(context));

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

    if (level < 100) {
        sBuilder.setSmallIcon(R.drawable.ic_stat_00_pct_charged + level);
    } else {
        sBuilder.setSmallIcon(R.drawable.ic_stat_z100_pct_charged);
    }

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

From source file:de.qspool.clementineremote.backend.downloader.DownloadManager.java

@SuppressLint("InlinedApi")
private void createNewActiveNotification() {
    mActiveNofiticationBuilder = new NotificationCompat.Builder(mContext)
            .setContentTitle(mContext.getString(R.string.download_noti_title))
            .setSmallIcon(R.drawable.ic_launcher).setOngoing(true)
            .setVisibility(Notification.VISIBILITY_PUBLIC);

    // Set the result intent
    mActiveNofiticationBuilder.setContentIntent(buildNotificationIntent());

    mActiveNofiticationBuilder.setPriority(NotificationCompat.PRIORITY_LOW);
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

public static void updateStatusBar(final Context context) {
    // In case status bar is not started yet call start method
    if (!isStatusBarShown) {
        startStatusBar(context);/*  w  w  w .  j ava  2  s  .c om*/
        return;
    }

    int now = Battery.getBatteryCurrentNow(context);
    int level = (int) (Inspector.getCurrentBatteryLevel() * 100);
    String title = context.getString(R.string.now) + ": " + now + " mA";
    String text = context.getString(R.string.notif_batteryhub_running);

    sBuilder.setContentTitle(title).setContentText(text).setAutoCancel(false).setOngoing(true)
            .setPriority(SettingsUtils.fetchNotificationsPriority(context));

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

    if (level < 100) {
        sBuilder.setSmallIcon(R.drawable.ic_stat_00_pct_charged + level);
    } else {
        sBuilder.setSmallIcon(R.drawable.ic_stat_z100_pct_charged);
    }

    LOGI(TAG, "Updating value of notification");

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

From source file:net.olejon.mdapp.MessageIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    final Context mContext = this;

    final MyTools mTools = new MyTools(mContext);

    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    int projectVersionCode = mTools.getProjectVersionCode();

    String device = mTools.getDevice();

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
            getString(R.string.project_website_uri) + "api/1/message/?version_code=" + projectVersionCode
                    + "&device=" + device,
            new Response.Listener<JSONObject>() {
                @SuppressLint("InlinedApi")
                @Override/*  w  w  w . j  a v  a 2  s  .  c  o  m*/
                public void onResponse(JSONObject response) {
                    try {
                        final long id = response.getLong("id");
                        final String title = response.getString("title");
                        final String message = response.getString("message");
                        final String bigMessage = response.getString("big_message");
                        final String button = response.getString("button");
                        final String uri = response.getString("uri");

                        final long lastId = mTools.getSharedPreferencesLong("MESSAGE_LAST_ID");

                        mTools.setSharedPreferencesLong("MESSAGE_LAST_ID", id);

                        if (lastId != 0 && id != lastId) {
                            Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                                    R.drawable.ic_launcher);

                            NotificationManagerCompat notificationManager = NotificationManagerCompat
                                    .from(mContext);
                            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
                                    mContext);

                            notificationBuilder.setWhen(mTools.getCurrentTime()).setAutoCancel(true)
                                    .setPriority(Notification.PRIORITY_HIGH)
                                    .setVisibility(Notification.VISIBILITY_PUBLIC)
                                    .setCategory(Notification.CATEGORY_MESSAGE).setLargeIcon(bitmap)
                                    .setSmallIcon(R.drawable.ic_local_hospital_white_24dp)
                                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                                    .setLights(Color.BLUE, 1000, 2000).setTicker(message).setContentTitle(title)
                                    .setContentText(message)
                                    .setStyle(new NotificationCompat.BigTextStyle().bigText(bigMessage));

                            if (!uri.equals("")) {
                                Intent launchIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                                PendingIntent launchPendingIntent = PendingIntent.getActivity(mContext, 0,
                                        launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);

                                notificationBuilder.setContentIntent(launchPendingIntent).addAction(
                                        R.drawable.ic_local_hospital_white_24dp, button, launchPendingIntent);
                            }

                            notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
                        }
                    } catch (Exception e) {
                        Log.e("MessageIntentService", Log.getStackTraceString(e));
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("MessageIntentService", error.toString());
                }
            });

    jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    requestQueue.add(jsonObjectRequest);
}

From source file:net.olejon.mdapp.NotificationsFromSlvIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    final Context mContext = this;

    final MyTools mTools = new MyTools(mContext);

    if (mTools.getDefaultSharedPreferencesBoolean("NOTIFICATIONS_FROM_SLV_NOTIFY")
            && mTools.isDeviceConnected()) {
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);

        int projectVersionCode = mTools.getProjectVersionCode();

        String device = mTools.getDevice();

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(
                getString(R.string.project_website_uri) + "api/1/notifications-from-slv/?first&version_code="
                        + projectVersionCode + "&device=" + device,
                new Response.Listener<JSONArray>() {
                    @SuppressLint("InlinedApi")
                    @Override/*  ww w  .  j a  va  2 s .c o  m*/
                    public void onResponse(JSONArray response) {
                        try {
                            final JSONObject notifications = response.getJSONObject(0);

                            final String title = notifications.getString("title");
                            final String message = notifications.getString("message");

                            final String lastTitle = mTools
                                    .getSharedPreferencesString("NOTIFICATIONS_FROM_SLV_LAST_TITLE");

                            if (!title.equals(lastTitle)) {
                                if (!lastTitle.equals("")) {
                                    Intent launchIntent = new Intent(mContext,
                                            NotificationsFromSlvActivity.class);
                                    PendingIntent launchPendingIntent = PendingIntent.getActivity(mContext, 0,
                                            launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);

                                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                                            R.drawable.ic_launcher);

                                    NotificationManagerCompat notificationManager = NotificationManagerCompat
                                            .from(mContext);
                                    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
                                            mContext);

                                    notificationBuilder.setWhen(mTools.getCurrentTime())
                                            .setPriority(Notification.PRIORITY_HIGH)
                                            .setVisibility(Notification.VISIBILITY_PUBLIC)
                                            .setCategory(Notification.CATEGORY_MESSAGE).setLargeIcon(bitmap)
                                            .setSmallIcon(R.drawable.ic_local_hospital_white_24dp)
                                            .setSound(RingtoneManager
                                                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                                            .setLights(Color.BLUE, 1000, 2000).setTicker(title)
                                            .setContentTitle(title).setContentText(message)
                                            .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
                                            .setContentIntent(launchPendingIntent)
                                            .addAction(R.drawable.ic_notifications_white_24dp,
                                                    getString(
                                                            R.string.service_notifications_from_slv_read_more),
                                                    launchPendingIntent);

                                    notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
                                }

                                mTools.setSharedPreferencesString("NOTIFICATIONS_FROM_SLV_LAST_TITLE", title);
                            }
                        } catch (Exception e) {
                            Log.e("NotificationsFromSlv", Log.getStackTraceString(e));
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("NotificationsFromSlv", error.toString());
                    }
                });

        jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        requestQueue.add(jsonArrayRequest);
    }
}

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

public static void batteryFullAlert(final Context context) {
    if (sNotificationManager == null) {
        sNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    }/*from  w  ww  .  j  a va  2  s  .c om*/

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_information_white_24dp).setContentTitle("Battery is full")
            .setContentText("Remove your phone from the charger").setAutoCancel(true).setOngoing(false)
            .setLights(Color.GREEN, 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);
    }

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

From source file:de.appplant.cordova.plugin.background.ForegroundService.java

/**
 * Create a notification as the visible part to be able to put the service
 * in a foreground state.//from w  w  w. j  a v  a 2s  .  c o  m
 *
 * @return
 *      A local ongoing notification which pending intent is bound to the
 *      main activity.
 */
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private Notification makeNotification() {
    JSONObject settings = BackgroundMode.getSettings();
    Context context = getApplicationContext();
    String pkgName = context.getPackageName();
    Intent intent = context.getPackageManager().getLaunchIntentForPackage(pkgName);

    notification = new Notification.Builder(context).setContentTitle(settings.optString("title", ""))
            .setContentText(settings.optString("text", "")).setTicker(settings.optString("ticker", ""))
            .setOngoing(true).setSmallIcon(getIconResId());

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        if (settings.optBoolean("isPublic") == true) {
            notification.setVisibility(Notification.VISIBILITY_PUBLIC);
        }

        if (!settings.optString("color").equals("")) {
            try {
                notification.setColor(Color.parseColor(settings.optString("color")));
            } catch (Exception e) {
                Log.e("BackgroundMode", settings.optString("color") + " is not a valid color");
            }
        }
    }

    if (intent != null && settings.optBoolean("resume")) {

        PendingIntent contentIntent = PendingIntent.getActivity(context, NOTIFICATION_ID, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        notification.setContentIntent(contentIntent);
    }

    if (Build.VERSION.SDK_INT < 16) {
        // Build notification for HoneyComb to ICS
        return notification.getNotification();
    } else {
        // Notification for Jellybean and above
        return notification.build();
    }
}