Java Code Examples for androidx.core.app.NotificationCompat#Builder

The following examples show how to use androidx.core.app.NotificationCompat#Builder . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AN2LinuxService.java    From an2linuxclient with GNU General Public License v3.0 6 votes vote down vote up
private void do_foreground() {
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(
            this, CHANNEL_ID_FOREGROUND_SERVICE
    );

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
        notificationBuilder.setCategory(Notification.CATEGORY_SERVICE);
    } else{
        notificationBuilder.setPriority(Notification.PRIORITY_MIN);
    }
    notificationBuilder.setOngoing(true);
    notificationBuilder.setSmallIcon(R.drawable.an2linux_icon);
    notificationBuilder.setTicker(getString(R.string.main_enable_service_notification_channel_name));
    notificationBuilder.setContentIntent(
            PendingIntent.getActivity(this, 0,
                    new Intent(this, MainSettingsActivity.class),
                    PendingIntent.FLAG_UPDATE_CURRENT)
    );
    Notification n = notificationBuilder.build();

    startForeground(NOTIFICATION_ID_FOREGROUND_SERVICE, n);
}
 
Example 2
Source File: UpdateService.java    From a with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 更新通知
 */
private void updateNotification(int state) {
    RxBus.get().post(RxBusTag.UPDATE_APK_STATE, state);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, MApplication.channelIdReadAloud)
            .setSmallIcon(R.drawable.ic_download)
            .setOngoing(true)
            .setContentTitle(getString(R.string.download_update))
            .setContentText(String.format(getString(R.string.progress_show), state, 100))
            .setContentIntent(getActivityPendingIntent());
    builder.addAction(R.drawable.ic_stop_black_24dp, getString(R.string.cancel), getThisServicePendingIntent());
    builder.setProgress(100, state, false);
    builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
    Notification notification = builder.build();
    int notificationId = 3425;
    startForeground(notificationId, notification);
}
 
Example 3
Source File: NotificationController.java    From NGA-CLIENT-VER-OPEN-SOURCE with GNU General Public License v2.0 6 votes vote down vote up
private void showMessageNotification() {
    Context context = ApplicationContextHolder.getContext();

    Intent intent = new Intent(context, MessageListActivity.class);

    PendingIntent pending = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = buildNotification(context);
    builder.setContentIntent(pending)
            .setTicker("有新的短消息,请查看")
            .setContentTitle("有新的短消息,请查看")
            .setContentText("有新的短消息,请查看");

    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    if (nm != null) {
        nm.notify(1000, builder.build()); // 通过通知管理器发送通知
    }
}
 
Example 4
Source File: MainSettingsActivity.java    From an2linuxclient with GNU General Public License v3.0 6 votes vote down vote up
private void displayNotificationHidingHelp() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, CHANNEL_ID_INFORMATION);

        notificationBuilder.setCategory(Notification.CATEGORY_MESSAGE);
        notificationBuilder.setSmallIcon(R.drawable.an2linux_icon);
        notificationBuilder.setTicker(getString(R.string.main_enable_service_information_notification_title));
        notificationBuilder.setContentIntent(
                PendingIntent.getActivity(this, 0,
                        new Intent(this, MainSettingsActivity.class),
                        PendingIntent.FLAG_UPDATE_CURRENT)
        );
        notificationBuilder.setAutoCancel(true);
        notificationBuilder.setContentTitle(getString(R.string.main_enable_service_information_notification_title));
        notificationBuilder.setContentText(getString(R.string.main_enable_service_information_notification_text));
        notificationBuilder.setStyle(new NotificationCompat.BigTextStyle()
                .bigText(getString(R.string.main_enable_service_information_notification_text)));

        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
        notificationManager.notify(NOTIFICATION_ID_HIDE_FOREGROUND_NOTIF, notificationBuilder.build());
    }
}
 
Example 5
Source File: MediaNotificationManager.java    From YouTube-In-Background with MIT License 6 votes vote down vote up
private void addPlayPauseAction(NotificationCompat.Builder builder)
{
    LogHelper.d(TAG, "updatePlayPauseAction");
    String label;
    int icon;
    PendingIntent intent;
    if (playbackState.getState() == STATE_PLAYING) {
        label = exoAudioService.getString(R.string.action_pause);
        icon = R.drawable.ic_pause_white_24dp;
        intent = pauseIntent;
    } else {
        label = exoAudioService.getString(R.string.action_play);
        icon = R.drawable.ic_play_arrow_white_24dp;
        intent = playIntent;
    }
    builder.addAction(new NotificationCompat.Action(icon, label, intent));
}
 
Example 6
Source File: ServiceSinkhole.java    From tracker-control-android with GNU General Public License v3.0 6 votes vote down vote up
private Notification getWaitingNotification() {
    Intent main = new Intent(this, ActivityMain.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, main, PendingIntent.FLAG_UPDATE_CURRENT);

    TypedValue tv = new TypedValue();
    getTheme().resolveAttribute(R.attr.colorPrimary, tv, true);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "foreground");
    builder.setSmallIcon(R.drawable.ic_rocket_white)
            .setContentIntent(pi)
            .setColor(tv.data)
            .setOngoing(true)
            .setAutoCancel(false);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        builder.setContentTitle(getString(R.string.msg_waiting));
    else
        builder.setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.msg_waiting));

    return builder.build();
}
 
Example 7
Source File: SyncManagerFragment.java    From dhis2-android-capture-app with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void showDeleteProgress() {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel mChannel = new NotificationChannel("wipe_notification", "Restart", NotificationManager.IMPORTANCE_HIGH);
        notificationManager.createNotificationChannel(mChannel);
    }
    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(context, "wipe_notification")
                    .setSmallIcon(R.drawable.ic_sync)
                    .setContentTitle(getString(R.string.wipe_data))
                    .setContentText(getString(R.string.please_wait))
                    .setOngoing(true)
                    .setAutoCancel(false)
                    .setPriority(NotificationCompat.PRIORITY_HIGH);

    notificationManager.notify(123456, notificationBuilder.build());
    presenter.wipeDb();

}
 
Example 8
Source File: LeanplumNotificationHelper.java    From Leanplum-Android-SDK with Apache License 2.0 6 votes vote down vote up
/**
 * If notification channels are supported this method will try to create
 * NotificationCompat.Builder with default notification channel if default channel id is provided.
 * If notification channels not supported this method will return NotificationCompat.Builder for
 * context.
 *
 * @param context The application context.
 * @param isNotificationChannelSupported True if notification channels are supported.
 * @return NotificationCompat.Builder for provided context or null.
 */
// NotificationCompat.Builder(Context context) constructor was deprecated in API level 26.
@SuppressWarnings("deprecation")
static NotificationCompat.Builder getDefaultCompatNotificationBuilder(Context context,
    boolean isNotificationChannelSupported) {
  if (!isNotificationChannelSupported) {
    return new NotificationCompat.Builder(context);
  }
  String channelId = LeanplumNotificationChannel.getDefaultNotificationChannelId(context);
  if (!TextUtils.isEmpty(channelId)) {
    return new NotificationCompat.Builder(context, channelId);
  } else {
    Log.w("Failed to post notification, there are no notification channels configured.");
    return null;
  }
}
 
Example 9
Source File: ProximityService.java    From Android-nRF-Toolbox with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Creates a notification showing information about a device that got disconnected.
 */
private void createLinkLossNotification(final BluetoothDevice device) {
    final NotificationCompat.Builder builder = getNotificationBuilder();
    builder.setColor(ContextCompat.getColor(this, R.color.orange));

    final Uri notificationUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
    // Make sure the sound is played even in DND mode
    builder.setSound(notificationUri, AudioManager.STREAM_ALARM);
    builder.setPriority(NotificationCompat.PRIORITY_HIGH);
    builder.setCategory(NotificationCompat.CATEGORY_ALARM);
    builder.setShowWhen(true);
    // An ongoing notification would not be shown on Android Wear.
    builder.setOngoing(false);
    // This notification is to be shown not in a group

    final String name = getDeviceName(device);
    builder.setContentTitle(getString(R.string.proximity_notification_link_loss_alert, name));
    builder.setTicker(getString(R.string.proximity_notification_link_loss_alert, name));

    final Notification notification = builder.build();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForeground(NOTIFICATION_ID, notification);
    } else {
        final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        nm.notify(device.getAddress(), NOTIFICATION_ID, notification);
    }
}
 
Example 10
Source File: AudioBookPlayService.java    From HaoReader with GNU General Public License v3.0 5 votes vote down vote up
private void showNotification(Bitmap cover) {
    final String contentTitle;
    final String name = bookShelfBean == null ? getString(R.string.app_name) : bookShelfBean.getBookInfoBean().getName();
    if (timerUntilFinish > 0) {
        contentTitle = String.format(Locale.getDefault(), "(%d分钟)%s", timerUntilFinish, name);
    } else {
        contentTitle = name;
    }
    final String contentText = bookShelfBean == null ? null : bookShelfBean.getDisplayDurChapterName();
    RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.layout_audio_notification);
    remoteViews.setTextViewText(R.id.tv_title, contentTitle);
    remoteViews.setTextViewText(R.id.tv_content, TextUtils.isEmpty(contentText) ? "即将为您播放" : contentText);
    if (isPause) {
        remoteViews.setImageViewResource(R.id.btn_pause, R.drawable.ic_play_white_24dp);
        remoteViews.setOnClickPendingIntent(R.id.btn_pause, getThisServicePendingIntent(ACTION_RESUME));
    } else {
        remoteViews.setImageViewResource(R.id.btn_pause, R.drawable.ic_pause_white_24dp);
        remoteViews.setOnClickPendingIntent(R.id.btn_pause, getThisServicePendingIntent(ACTION_PAUSE));
    }

    remoteViews.setOnClickPendingIntent(R.id.btn_previous, getThisServicePendingIntent(ACTION_PREVIOUS));
    remoteViews.setOnClickPendingIntent(R.id.btn_next, getThisServicePendingIntent(ACTION_NEXT));
    remoteViews.setOnClickPendingIntent(R.id.btn_stop, getThisServicePendingIntent(ACTION_STOP));

    remoteViews.setImageViewBitmap(R.id.iv_cover, cover);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, MApplication.channelIdAudioBook)
            .setSmallIcon(R.drawable.ic_volume_up_black_24dp)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
            .setContentTitle(contentTitle)
            .setContentText(TextUtils.isEmpty(contentText) ? "即将为您播放" : contentText)
            .setOngoing(true)
            .setWhen(System.currentTimeMillis())
            .setCustomBigContentView(remoteViews)
            .setContentIntent(getAudioActivityPendingIntent());
    startForeground(notificationId, builder.build());
}
 
Example 11
Source File: InsightAlertService.java    From AndroidAPS with GNU Affero General Public License v3.0 5 votes vote down vote up
private void showNotification(Alert alert) {
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, LocalInsightPlugin.ALERT_CHANNEL_ID);

    notificationBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
    notificationBuilder.setCategory(NotificationCompat.CATEGORY_ALARM);
    notificationBuilder.setVibrate(new long[0]);
    notificationBuilder.setShowWhen(false);
    notificationBuilder.setOngoing(true);
    notificationBuilder.setOnlyAlertOnce(true);
    notificationBuilder.setAutoCancel(false);
    notificationBuilder.setSmallIcon(AlertUtilsKt.getAlertIcon(alert.getAlertCategory()));

    notificationBuilder.setContentTitle(AlertUtilsKt.getAlertCode(alert.getAlertType()) + " – " + AlertUtilsKt.getAlertTitle(alert.getAlertType()));
    String description = AlertUtilsKt.getAlertDescription(alert);
    if (description != null)
        notificationBuilder.setContentText(Html.fromHtml(description).toString());

    Intent fullScreenIntent = new Intent(this, InsightAlertActivity.class);
    PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    notificationBuilder.setFullScreenIntent(fullScreenPendingIntent, true);

    switch (alert.getAlertStatus()) {
        case ACTIVE:
            Intent muteIntent = new Intent(this, InsightAlertService.class).putExtra("command", "mute");
            PendingIntent mutePendingIntent = PendingIntent.getService(this, 1, muteIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            notificationBuilder.addAction(0, MainApp.gs(R.string.mute_alert), mutePendingIntent);
        case SNOOZED:
            Intent confirmIntent = new Intent(this, InsightAlertService.class).putExtra("command", "confirm");
            PendingIntent confirmPendingIntent = PendingIntent.getService(this, 2, confirmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            notificationBuilder.addAction(0, MainApp.gs(R.string.confirm), confirmPendingIntent);
    }

    Notification notification = notificationBuilder.build();
    NotificationManagerCompat.from(this).notify(NOTIFICATION_ID, notification);
    startForeground(NOTIFICATION_ID, notification);
}
 
Example 12
Source File: SubscriptionsFeedFragment.java    From SkyTube with GNU General Public License v3.0 5 votes vote down vote up
private void showNotification() {
		// Sets an ID for the notification, so it can be updated.
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
			NotificationManager mNotificationManager =
					(NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);

			NotificationChannel mChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
			mChannel.setSound(null,null);
			// Create a notification and set the notification channel.
			Notification notification = new Notification.Builder(getContext(), NOTIFICATION_CHANNEL_NAME)
					.setSmallIcon(R.drawable.ic_notification_icon)
					.setContentTitle(getString(R.string.fetching_subscription_videos))
					.setContentText(String.format(getContext().getString(R.string.fetched_videos_from_channels), numVideosFetched, numChannelsFetched, numChannelsSubscribed))
					.setChannelId(NOTIFICATION_CHANNEL_ID)
					.build();
			mNotificationManager.createNotificationChannel(mChannel);

// Issue the notification.
			mNotificationManager.notify(NOTIFICATION_ID , notification);
		} else {
			final Intent emptyIntent = new Intent();
			PendingIntent pendingIntent = PendingIntent.getActivity(getContext(), 1, emptyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
			NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext(), "")
					.setSmallIcon(R.drawable.ic_notification_icon)
					.setContentTitle(getString(R.string.fetching_subscription_videos))
					.setContentText(String.format(getContext().getString(R.string.fetched_videos_from_channels), numVideosFetched, numChannelsFetched, numChannelsSubscribed))
					.setPriority(NotificationCompat.FLAG_ONGOING_EVENT)
					.setContentIntent(pendingIntent);


			NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
			notificationManager.notify(NOTIFICATION_ID, builder.build());
		}
	}
 
Example 13
Source File: BigPictureSocialIntentService.java    From user-interface-samples with Apache License 2.0 4 votes vote down vote up
private NotificationCompat.Builder recreateBuilderWithBigPictureStyle() {

        // Main steps for building a BIG_PICTURE_STYLE notification (for more detailed comments on
        // building this notification, check MainActivity.java):
        //      0. Get your data
        //      1. Build the BIG_PICTURE_STYLE
        //      2. Set up main Intent for notification
        //      3. Set up RemoteInput, so users can input (keyboard and voice) from notification
        //      4. Build and issue the notification

        // 0. Get your data (everything unique per Notification)
        MockDatabase.BigPictureStyleSocialAppData bigPictureStyleSocialAppData =
                MockDatabase.getBigPictureStyleData();

        // 1. Build the BIG_PICTURE_STYLE
        BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle()
                .bigPicture(
                        BitmapFactory.decodeResource(
                                getResources(),
                                bigPictureStyleSocialAppData.getBigImage()))
                .setBigContentTitle(bigPictureStyleSocialAppData.getBigContentTitle())
                .setSummaryText(bigPictureStyleSocialAppData.getSummaryText());

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

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(BigPictureSocialMainActivity.class);
        stackBuilder.addNextIntent(mainIntent);

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

        // 3. Set up RemoteInput, so users can input (keyboard and voice) from notification
        String replyLabel = getString(R.string.reply_label);
        RemoteInput remoteInput =
                new RemoteInput.Builder(BigPictureSocialIntentService.EXTRA_COMMENT)
                        .setLabel(replyLabel)
                        .setChoices(bigPictureStyleSocialAppData.getPossiblePostResponses())
                        .build();

        PendingIntent replyActionPendingIntent;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Intent intent = new Intent(this, BigPictureSocialIntentService.class);
            intent.setAction(BigPictureSocialIntentService.ACTION_COMMENT);
            replyActionPendingIntent = PendingIntent.getService(this, 0, intent, 0);

        } else {
            replyActionPendingIntent = mainPendingIntent;
        }

        NotificationCompat.Action replyAction =
                new NotificationCompat.Action.Builder(
                        R.drawable.ic_reply_white_18dp,
                        replyLabel,
                        replyActionPendingIntent)
                        .addRemoteInput(remoteInput)
                        .build();

        // 4. Build and issue the notification
        NotificationCompat.Builder notificationCompatBuilder =
                new NotificationCompat.Builder(getApplicationContext());

        GlobalNotificationBuilder.setNotificationCompatBuilderInstance(notificationCompatBuilder);

        notificationCompatBuilder
                .setStyle(bigPictureStyle)
                .setContentTitle(bigPictureStyleSocialAppData.getContentTitle())
                .setContentText(bigPictureStyleSocialAppData.getContentText())
                .setSmallIcon(R.drawable.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(
                        getResources(),
                        R.drawable.ic_person_black_48dp))
                .setContentIntent(mainPendingIntent)
                .setColor(getResources().getColor(R.color.colorPrimary))
                .setSubText(Integer.toString(1))
                .addAction(replyAction)
                .setCategory(Notification.CATEGORY_SOCIAL)
                .setPriority(Notification.PRIORITY_HIGH)
                .setVisibility(Notification.VISIBILITY_PRIVATE);

        // If the phone is in "Do not disturb mode, the user will still be notified if
        // the sender(s) is starred as a favorite.
        for (String name : bigPictureStyleSocialAppData.getParticipants()) {
            notificationCompatBuilder.addPerson(name);
        }

        return notificationCompatBuilder;
    }
 
Example 14
Source File: MessagingIntentService.java    From user-interface-samples with Apache License 2.0 4 votes vote down vote up
/** Handles action for replying to messages from the notification. */
private void handleActionReply(CharSequence replyCharSequence) {
    Log.d(TAG, "handleActionReply(): " + replyCharSequence);

    if (replyCharSequence != null) {

        // TODO: Asynchronously save your message to Database and servers.

        /*
         * You have two options for updating your notification (this class uses approach #2):
         *
         *  1. Use a new NotificationCompatBuilder to create the Notification. This approach
         *  requires you to get *ALL* the information that existed in the previous
         *  Notification (and updates) and pass it to the builder. This is the approach used in
         *  the MainActivity.
         *
         *  2. Use the original NotificationCompatBuilder to create the Notification. This
         *  approach requires you to store a reference to the original builder. The benefit is
         *  you only need the new/updated information. In our case, the reply from the user
         *  which we already have here.
         *
         *  IMPORTANT NOTE: You shouldn't save/modify the resulting Notification object using
         *  its member variables and/or legacy APIs. If you want to retain anything from update
         *  to update, retain the Builder as option 2 outlines.
         */

        // Retrieves NotificationCompat.Builder used to create initial Notification
        NotificationCompat.Builder notificationCompatBuilder =
                GlobalNotificationBuilder.getNotificationCompatBuilderInstance();

        // Recreate builder from persistent state if app process is killed
        if (notificationCompatBuilder == null) {
            // Note: New builder set globally in the method
            notificationCompatBuilder = recreateBuilderWithMessagingStyle();
        }

        // Since we are adding to the MessagingStyle, we need to first retrieve the
        // current MessagingStyle from the Notification itself.
        Notification notification = notificationCompatBuilder.build();
        MessagingStyle messagingStyle =
                NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(
                        notification);

        // Add new message to the MessagingStyle. Set last parameter to null for responses
        // from user.
        messagingStyle.addMessage(replyCharSequence, System.currentTimeMillis(), (Person) null);

        // Updates the Notification
        notification = notificationCompatBuilder.setStyle(messagingStyle).build();

        // Pushes out the updated Notification
        NotificationManagerCompat notificationManagerCompat =
                NotificationManagerCompat.from(getApplicationContext());
        notificationManagerCompat.notify(StandaloneMainActivity.NOTIFICATION_ID, notification);
    }
}
 
Example 15
Source File: NotificationHelper.java    From grblcontroller with GNU General Public License v3.0 4 votes vote down vote up
public void notify(int id, NotificationCompat.Builder notification) {
    getNotificationManager().notify(id, notification.build());
}
 
Example 16
Source File: BigPictureSocialIntentService.java    From android-Notifications with Apache License 2.0 4 votes vote down vote up
private NotificationCompat.Builder recreateBuilderWithBigPictureStyle() {

        // Main steps for building a BIG_PICTURE_STYLE notification (for more detailed comments on
        // building this notification, check MainActivity.java):
        //      0. Get your data
        //      1. Build the BIG_PICTURE_STYLE
        //      2. Set up main Intent for notification
        //      3. Set up RemoteInput, so users can input (keyboard and voice) from notification
        //      4. Build and issue the notification

        // 0. Get your data (everything unique per Notification)
        MockDatabase.BigPictureStyleSocialAppData bigPictureStyleSocialAppData =
                MockDatabase.getBigPictureStyleData();

        // 1. Build the BIG_PICTURE_STYLE
        BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle()
                .bigPicture(
                        BitmapFactory.decodeResource(
                                getResources(),
                                bigPictureStyleSocialAppData.getBigImage()))
                .setBigContentTitle(bigPictureStyleSocialAppData.getBigContentTitle())
                .setSummaryText(bigPictureStyleSocialAppData.getSummaryText());

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

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(BigPictureSocialMainActivity.class);
        stackBuilder.addNextIntent(mainIntent);

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

        // 3. Set up RemoteInput, so users can input (keyboard and voice) from notification
        String replyLabel = getString(R.string.reply_label);
        RemoteInput remoteInput =
                new RemoteInput.Builder(BigPictureSocialIntentService.EXTRA_COMMENT)
                        .setLabel(replyLabel)
                        .setChoices(bigPictureStyleSocialAppData.getPossiblePostResponses())
                        .build();

        PendingIntent replyActionPendingIntent;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Intent intent = new Intent(this, BigPictureSocialIntentService.class);
            intent.setAction(BigPictureSocialIntentService.ACTION_COMMENT);
            replyActionPendingIntent = PendingIntent.getService(this, 0, intent, 0);

        } else {
            replyActionPendingIntent = mainPendingIntent;
        }

        NotificationCompat.Action replyAction =
                new NotificationCompat.Action.Builder(
                        R.drawable.ic_reply_white_18dp,
                        replyLabel,
                        replyActionPendingIntent)
                        .addRemoteInput(remoteInput)
                        .build();

        // 4. Build and issue the notification
        NotificationCompat.Builder notificationCompatBuilder =
                new NotificationCompat.Builder(getApplicationContext());

        GlobalNotificationBuilder.setNotificationCompatBuilderInstance(notificationCompatBuilder);

        notificationCompatBuilder
                .setStyle(bigPictureStyle)
                .setContentTitle(bigPictureStyleSocialAppData.getContentTitle())
                .setContentText(bigPictureStyleSocialAppData.getContentText())
                .setSmallIcon(R.drawable.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(
                        getResources(),
                        R.drawable.ic_person_black_48dp))
                .setContentIntent(mainPendingIntent)
                .setColor(getResources().getColor(R.color.colorPrimary))
                .setSubText(Integer.toString(1))
                .addAction(replyAction)
                .setCategory(Notification.CATEGORY_SOCIAL)
                .setPriority(Notification.PRIORITY_HIGH)
                .setVisibility(Notification.VISIBILITY_PRIVATE);

        // If the phone is in "Do not disturb mode, the user will still be notified if
        // the sender(s) is starred as a favorite.
        for (String name : bigPictureStyleSocialAppData.getParticipants()) {
            notificationCompatBuilder.addPerson(name);
        }

        return notificationCompatBuilder;
    }
 
Example 17
Source File: MessagingIntentService.java    From android-Notifications with Apache License 2.0 4 votes vote down vote up
/** Handles action for replying to messages from the notification. */
private void handleActionReply(CharSequence replyCharSequence) {
    Log.d(TAG, "handleActionReply(): " + replyCharSequence);

    if (replyCharSequence != null) {

        // TODO: Asynchronously save your message to Database and servers.

        /*
         * You have two options for updating your notification (this class uses approach #2):
         *
         *  1. Use a new NotificationCompatBuilder to create the Notification. This approach
         *  requires you to get *ALL* the information that existed in the previous
         *  Notification (and updates) and pass it to the builder. This is the approach used in
         *  the MainActivity.
         *
         *  2. Use the original NotificationCompatBuilder to create the Notification. This
         *  approach requires you to store a reference to the original builder. The benefit is
         *  you only need the new/updated information. In our case, the reply from the user
         *  which we already have here.
         *
         *  IMPORTANT NOTE: You shouldn't save/modify the resulting Notification object using
         *  its member variables and/or legacy APIs. If you want to retain anything from update
         *  to update, retain the Builder as option 2 outlines.
         */

        // Retrieves NotificationCompat.Builder used to create initial Notification
        NotificationCompat.Builder notificationCompatBuilder =
                GlobalNotificationBuilder.getNotificationCompatBuilderInstance();

        // Recreate builder from persistent state if app process is killed
        if (notificationCompatBuilder == null) {
            // Note: New builder set globally in the method
            notificationCompatBuilder = recreateBuilderWithMessagingStyle();
        }

        // Since we are adding to the MessagingStyle, we need to first retrieve the
        // current MessagingStyle from the Notification itself.
        Notification notification = notificationCompatBuilder.build();
        MessagingStyle messagingStyle =
                NotificationCompat.MessagingStyle.extractMessagingStyleFromNotification(
                        notification);

        // Add new message to the MessagingStyle. Set last parameter to null for responses
        // from user.
        messagingStyle.addMessage(replyCharSequence, System.currentTimeMillis(), (Person) null);

        // Updates the Notification
        notification = notificationCompatBuilder.setStyle(messagingStyle).build();

        // Pushes out the updated Notification
        NotificationManagerCompat notificationManagerCompat =
                NotificationManagerCompat.from(getApplicationContext());
        notificationManagerCompat.notify(MainActivity.NOTIFICATION_ID, notification);
    }
}
 
Example 18
Source File: LbrynetMessagingService.java    From lbry-android with MIT License 4 votes vote down vote up
/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 */
private void sendNotification(String title, String messageBody, String type, String url, String name,
                              String contentTitle, String channelUrl, String publishTime) {
    //Intent intent = new Intent(this, MainActivity.class);
    //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    if (url == null) {
        if (TYPE_REWARD.equals(type)) {
            url = "lbry://?rewards";
        } else {
            // default to home page
            url = "lbry://?discover";
        }
    }

    Intent launchIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    launchIntent.putExtra("notification_name", name);
    launchIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, launchIntent, PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                    .setColor(ContextCompat.getColor(this, R.color.lbryGreen))
                    .setSmallIcon(R.drawable.ic_lbry)
                    .setContentTitle(title)
                    .setContentText(messageBody)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);

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

    // Since android Oreo notification channel is needed.
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(
                NOTIFICATION_CHANNEL_ID, "LBRY Engagement", NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(channel);
    }

    notificationManager.notify(3, notificationBuilder.build());
}
 
Example 19
Source File: MotivationAlertReceiver.java    From privacy-friendly-interval-timer with GNU General Public License v3.0 4 votes vote down vote up
private void motivate() {

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

        //Choose a motivation text
        Set<String> defaultStringSet = new HashSet<>(Arrays.asList(context.getResources().getStringArray(R.array.pref_default_notification_motivation_alert_messages)));
        List<String> motivationTexts = new ArrayList<>(preferences.getStringSet(context.getString(R.string.pref_notification_motivation_alert_texts),  defaultStringSet));

        if (motivationTexts.size() == 0) {
            Log.e(LOG_CLASS, "Motivation texts are empty. Cannot notify the user.");

            //Reschedule alarm for tomorrow
            if(NotificationHelper.isMotivationAlertEnabled(context)){
                NotificationHelper.setMotivationAlert(context);
            }
            return;
        }

        Collections.shuffle(motivationTexts);
        String motivationText = motivationTexts.get(0);


        // Build the notification
        NotificationManager notificationManager = (NotificationManager) context.getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

        Intent intent = new Intent(context, MainActivity.class);
        intent.setAction(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext())
                .setSmallIcon(R.drawable.ic_notification)
                .setColor(ContextCompat.getColor(context, R.color.colorAccent))
                .setContentTitle(context.getString(R.string.reminder_notification_title))
                .setContentText(motivationText)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .setLights(ContextCompat.getColor(context, R.color.colorPrimary), 1000, 1000);
        // Notify
        notificationManager.notify(NOTIFICATION_ID, mBuilder.build());

        //Reschedule alarm for tomorrow
        if(NotificationHelper.isMotivationAlertEnabled(context)){
            NotificationHelper.setMotivationAlert(context);
        }
    }
 
Example 20
Source File: NotificationReceiver.java    From Pocket-Plays-for-Twitch with GNU General Public License v3.0 4 votes vote down vote up
private void createStreamSummaryNotification(Bitmap largeIcon, NotificationFetchData notificationData, NotificationManager manager, Context context) {
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MyStreamsActivity.class);
    stackBuilder.addNextIntent(new Intent(context, MyStreamsActivity.class));
    PendingIntent clickIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationTextData notificationText = constructMainNotificationText(notificationData, context);
    if (notificationText.getTitle().isEmpty() || notificationText.getContent().isEmpty()) {
        return;
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, context.getString(R.string.live_streamer_notification_id))
            .setAutoCancel(true)
            .setContentTitle(notificationText.getTitle())
            .setContentText(notificationText.getContent())
            .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationText.getContent()))
            .setGroup(GROUP_KEY)
            .setGroupSummary(true)
            .setContentIntent(clickIntent)
            .setSubText(notificationText.getSubtext())
            .setLargeIcon(largeIcon)
            .setSmallIcon(R.drawable.ic_notification_icon_refresh)
            .setColor(ContextCompat.getColor(context, R.color.primary));

    Settings settings = new Settings(context);
    boolean toVibrate = settings.getNotificationsVibrations();
    boolean toWakeScreen = settings.getNotificationsScreenWake();
    boolean toPlaySound = settings.getNotificationsSound();
    boolean toBlinkLED = settings.getNotificationsLED();
    boolean isQuietHoursEnabled = settings.getNotificationsQuietHours();
    boolean isInQuietHours = isQuietHoursEnabled && isInQuietTime(settings);

    if(toWakeScreen && !isInQuietHours) {
        PowerManager.WakeLock screenOn = null;
        PowerManager powerManager = ((PowerManager) context.getSystemService(Context.POWER_SERVICE));
        if (powerManager != null) {
            screenOn = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "pocketplays:lock");
        }
        if (screenOn != null) {
            screenOn.acquire(2000);
        }
    }

    if(toVibrate && !isInQuietHours) {
        // Set the notification to vibrate
        final int DELAY = 0;
        final int VIBRATE_DURATION = 100;
        mBuilder.setVibrate(new long[] {
                DELAY,
                VIBRATE_DURATION,
                0,
                0
        });
    }
    if(toPlaySound && !isInQuietHours)
        mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

    if(toBlinkLED && !isInQuietHours)
        mBuilder.setLights(Color.BLUE, 5000, 5000);

    manager.notify(NOTIFICATION_ID, mBuilder.build());
}