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

The following examples show how to use androidx.core.app.NotificationCompat#Action . 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: NotificationActionUtils.java    From abnd-track-pomodoro-timer-app with MIT License 6 votes vote down vote up
/**
 * @param currentlyRunningServiceType The next service that shall be run
 * @return Returns Action Buttons and assigns pendingIntents to Actions
 */
public static NotificationCompat.Action getIntervalAction(int currentlyRunningServiceType,
                                                          Context context) {

    switch (currentlyRunningServiceType) {
        case TAMETU:
            return new NotificationCompat.Action(
                    R.drawable.play,
                    context.getString(R.string.start_tametu),
                    getPendingIntent(TAMETU, INTENT_VALUE_START, context));
        case SHORT_BREAK:
            return new NotificationCompat.Action(
                    R.drawable.short_break,
                    context.getString(R.string.start_short_break),
                    getPendingIntent(SHORT_BREAK, INTENT_VALUE_SHORT_BREAK, context));
        case LONG_BREAK:
            return new NotificationCompat.Action(
                    R.drawable.long_break,
                    context.getString(R.string.start_long_break),
                    getPendingIntent(LONG_BREAK, INTENT_VALUE_LONG_BREAK, context));
        default:
            return null;
    }

}
 
Example 2
Source File: BackgroundAudioService.java    From YouTube-In-Background with MIT License 5 votes vote down vote up
/**
 * Generates specific action with parameters below
 *
 * @param icon         the icon number
 * @param title        the title of the notification
 * @param intentAction the action
 * @return NotificationCompat.Action
 */
private NotificationCompat.Action generateAction(int icon, String title, String intentAction)
{
    Context context = getApplicationContext();
    Intent intent = new Intent(context, BackgroundAudioService.class);
    intent.setAction(intentAction);
    PendingIntent pendingIntent = PendingIntent.getService(context, 1, intent, 0);

    return new NotificationCompat.Action.Builder(icon, title, pendingIntent).build();
}
 
Example 3
Source File: CallNotificationBuilder.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
private static NotificationCompat.Action getActivityNotificationAction(@NonNull Context context, @NonNull String action,
                                                                       @DrawableRes int iconResId, @StringRes int titleResId)
{
  Intent intent = new Intent(context, WebRtcCallActivity.class);
  intent.setAction(action);

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

  return new NotificationCompat.Action(iconResId, context.getString(titleResId), pendingIntent);
}
 
Example 4
Source File: CallNotificationBuilder.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private static NotificationCompat.Action getServiceNotificationAction(Context context, String action, int iconResId, int titleResId) {
    Intent intent = new Intent(context, WebRtcCallService.class);
    intent.setAction(action);
    PendingIntent pendingIntent = PendingIntent.getService(context, REQUEST_SERVICE_ACTION, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    return new NotificationCompat.Action(iconResId, context.getString(titleResId), pendingIntent);
}
 
Example 5
Source File: BackgroundExoAudioService.java    From YouTube-In-Background with MIT License 5 votes vote down vote up
/**
 * Generates specific action with parameters below
 *
 * @param icon         the icon number
 * @param title        the title of the notification
 * @param intentAction the action
 * @return NotificationCompat.Action
 */
private NotificationCompat.Action generateAction(int icon, String title, String intentAction)
{
    Context context = getApplicationContext();
    Intent intent = new Intent(context, BackgroundExoAudioService.class);
    intent.setAction(intentAction);
    PendingIntent pendingIntent = PendingIntent.getService(context, 1, intent, 0);

    return new NotificationCompat.Action.Builder(icon, title, pendingIntent).build();
}
 
Example 6
Source File: WearableNotificationWithVoice.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Action buildWearableAction() {
    String replyLabel = mContext.getString(replyLabelResourceId);
    RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY).setLabel(replyLabel).build();
    // Create an intent for the reply action
    if (pendingIntent == null) {
        Intent replyIntent = new Intent(mContext, notificationHandler);
        pendingIntent = PendingIntent.getActivity(mContext, (int) (System.currentTimeMillis() & 0xfffffff), replyIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    }
    // Create the reply action and add the remote input
    NotificationCompat.Action action = new NotificationCompat.Action.Builder(actionIconResId,
            mContext.getString(actionTitleId), pendingIntent).addRemoteInput(remoteInput).build();
    return action;
}
 
Example 7
Source File: PlayerService.java    From Pocket-Plays-for-Twitch with GNU General Public License v3.0 5 votes vote down vote up
private void buildNotification( NotificationCompat.Action action ) {
	lastNotificationAction = action;

	Intent intent = new Intent( getApplicationContext(), PlayerService.class );
	intent.setAction( ACTION_STOP );
	PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);

	Class toClass = isVod ? VODActivity.class : LiveStreamActivity.class;
	TaskStackBuilder stackBuilder = TaskStackBuilder.create(this).addParentStack(toClass).addNextIntent(mNotificationIntent);
	PendingIntent onClickPendingIntent = stackBuilder.getPendingIntent(
			0,
			PendingIntent.FLAG_UPDATE_CURRENT
	);

	NotificationCompat.Builder noti = new NotificationCompat.Builder( this, getString(R.string.stream_cast_notification_id) )
									.setSmallIcon( R.drawable.ic_notification_icon_refresh )
									.setContentTitle( mChannelInfo.getDisplayName() )
									.setDeleteIntent( pendingIntent )
									.addAction(action)
									.addAction(generateAction(R.drawable.ic_clear_black_36dp, getString(R.string.stop_lower), ACTION_STOP))
									.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
													  .setMediaSession(mediaSession.getSessionToken())
													  .setShowCancelButton(true)
													  .setShowActionsInCompactView(0,1)
									)
									.setShowWhen(false)
									.setAutoCancel(false)
									.setContentIntent(onClickPendingIntent);

	if (mChannelInfo.getLogoImage() != null) {
		noti.setLargeIcon(mChannelInfo.getLogoImage());
	}

	NotificationManager notificationManager = (NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE );
	if (notificationManager == null) return;
	notificationManager.notify( NOTIFICATION_ID, noti.build() );
}
 
Example 8
Source File: TtsService.java    From android-app with GNU General Public License v3.0 4 votes vote down vote up
private NotificationCompat.Action generateAction(int icon, int title, long action) {
    String titleString = getString(title);
    PendingIntent pendingIntent = generateActionIntent(action);
    return new NotificationCompat.Action(icon, titleString, pendingIntent);
}
 
Example 9
Source File: BackgroundAudioService.java    From YouTube-In-Background with MIT License 4 votes vote down vote up
/**
     * Builds notification panel with buttons and info on it
     *
     * @param action Action to be applied
     */

    private void buildNotification(NotificationCompat.Action action)
    {
        final MediaStyle style = new MediaStyle();

        Intent intent = new Intent(getApplicationContext(), BackgroundAudioService.class);
        intent.setAction(ACTION_STOP);
        PendingIntent stopPendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);

        Intent clickIntent = new Intent(this, MainActivity.class);
        clickIntent.setAction(Intent.ACTION_MAIN);
        clickIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent clickPendingIntent = PendingIntent.getActivity(this, 0, clickIntent, 0);

        notificationBuilder = new NotificationCompat.Builder(this);
        notificationBuilder.setSmallIcon(R.drawable.ic_notification);
        notificationBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        notificationBuilder.setContentTitle(currentVideo.getTitle());
        notificationBuilder.setContentInfo(currentVideo.getDuration());
        notificationBuilder.setUsesChronometer(true);
        notificationBuilder.setContentIntent(clickPendingIntent);
        notificationBuilder.setDeleteIntent(stopPendingIntent);
//        notificationBuilder.setOngoing(true);
        notificationBuilder.setSubText(Utils.formatViewCount(currentVideo.getViewCount()));
        notificationBuilder.setStyle(style);

        //load bitmap for largeScreen
        if (currentVideo.getThumbnailURL() != null && !currentVideo.getThumbnailURL().isEmpty()) {
            Picasso.with(this)
                    .load(currentVideo.getThumbnailURL())
                    .resize(Config.MAX_WIDTH_ICON, Config.MAX_HEIGHT_ICON)
                    .centerCrop()
                    .into(target);
        }

        notificationBuilder.addAction(generateIntentAction(ACTION_PREVIOUS));
        notificationBuilder.addAction(generateIntentAction(ACTION_NEXT));
//        notificationBuilder.updateAction(generateAction(
//                R.drawable.ic_skip_previous_white_24dp,
//                getApplicationContext().getString(R.string.action_previous),
//                ACTION_PREVIOUS
//        ));
//        notificationBuilder.updateAction(generateAction(
//                R.drawable.ic_skip_next_white_24dp,
//                getApplicationContext().getString(R.string.action_next),
//                CUSTOM_ACTION_NEXT));
        notificationBuilder.addAction(action);
        LogHelper.e(TAG, "setNotificationPlaybackState. mediaPlayer=" + mediaPlayer);
        setNotificationPlaybackState(notificationBuilder);

        style.setShowActionsInCompactView(0, 1, 2);

        NotificationManager notificationManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
    }
 
Example 10
Source File: MediaScannerService.java    From odyssey with GNU General Public License v3.0 4 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null && intent.getAction().equals(ACTION_START_MEDIASCANNING)) {
        mRemainingFiles = new ArrayList<>();

        mAbort = false;
        FileModel directory = null;

        // read path to directory from extras
        Bundle extras = intent.getExtras();
        if (extras != null) {
            String startDirectory = extras.getString(BUNDLE_KEY_DIRECTORY);

            directory = new FileModel(startDirectory);
        }

        if (BuildConfig.DEBUG) {
            Log.v(TAG, "start mediascanning");
        }

        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        mWakelock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "odyssey:wakelock:mediascanner");

        mWakelock.acquire();

        if (mBroadcastReceiver == null) {
            mBroadcastReceiver = new ActionReceiver();

            // Create a filter to only handle certain actions
            IntentFilter intentFilter = new IntentFilter();

            intentFilter.addAction(ACTION_CANCEL_MEDIASCANNING);

            registerReceiver(mBroadcastReceiver, intentFilter);
        }

        // create notification
        mBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setContentTitle(getString(R.string.mediascanner_notification_title))
                .setProgress(0, 0, true)
                .setSmallIcon(R.drawable.odyssey_notification);

        openChannel();

        mBuilder.setOngoing(true);

        // Cancel action
        Intent nextIntent = new Intent(MediaScannerService.ACTION_CANCEL_MEDIASCANNING);
        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action cancelAction = new NotificationCompat.Action.Builder(R.drawable.ic_close_24dp, getString(R.string.dialog_action_cancel), nextPendingIntent).build();

        mBuilder.addAction(cancelAction);

        Notification notification = mBuilder.build();
        startForeground(NOTIFICATION_ID, notification);
        mNotificationManager.notify(NOTIFICATION_ID, notification);

        // start scanning
        if (null != directory) {
            scanDirectory(this, directory);
        }
    }

    return START_NOT_STICKY;
}
 
Example 11
Source File: NotificationBuilder.java    From libcommon with Apache License 2.0 4 votes vote down vote up
@Override
public NotificationBuilder addAction(final NotificationCompat.Action action) {
	super.addAction(action);
	return this;
}
 
Example 12
Source File: PlayerService.java    From Pocket-Plays-for-Twitch with GNU General Public License v3.0 4 votes vote down vote up
private NotificationCompat.Action generateAction( int icon, String title, String intentAction ) {
	Intent intent = new Intent( getApplicationContext(), PlayerService.class );
	intent.setAction( intentAction );
	PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 1, intent, 0);
	return new NotificationCompat.Action.Builder( icon, title, pendingIntent ).build();
}
 
Example 13
Source File: InstallService.java    From aptoide-client-v8 with GNU General Public License v3.0 4 votes vote down vote up
@NonNull private NotificationCompat.Action getDownloadManagerAction(int requestCode) {
  return getAction(R.drawable.ic_manager, getString(R.string.open_apps_manager),
      getOpenDownloadManagerPendingIntent(requestCode));
}
 
Example 14
Source File: ServiceSinkhole.java    From NetGuard with GNU General Public License v3.0 4 votes vote down vote up
public void notifyNewApplication(int uid) {
    if (uid < 0)
        return;

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    try {
        // Get application name
        String name = TextUtils.join(", ", Util.getApplicationNames(uid, this));

        // Get application info
        PackageManager pm = getPackageManager();
        String[] packages = pm.getPackagesForUid(uid);
        if (packages == null || packages.length < 1)
            throw new PackageManager.NameNotFoundException(Integer.toString(uid));
        boolean internet = Util.hasInternet(uid, this);

        // Build notification
        Intent main = new Intent(this, ActivityMain.class);
        main.putExtra(ActivityMain.EXTRA_REFRESH, true);
        main.putExtra(ActivityMain.EXTRA_SEARCH, Integer.toString(uid));
        PendingIntent pi = PendingIntent.getActivity(this, uid, main, PendingIntent.FLAG_UPDATE_CURRENT);

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

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            builder.setCategory(NotificationCompat.CATEGORY_STATUS)
                    .setVisibility(NotificationCompat.VISIBILITY_SECRET);

        // Get defaults
        SharedPreferences prefs_wifi = getSharedPreferences("wifi", Context.MODE_PRIVATE);
        SharedPreferences prefs_other = getSharedPreferences("other", Context.MODE_PRIVATE);
        boolean wifi = prefs_wifi.getBoolean(packages[0], prefs.getBoolean("whitelist_wifi", true));
        boolean other = prefs_other.getBoolean(packages[0], prefs.getBoolean("whitelist_other", true));

        // Build Wi-Fi action
        Intent riWifi = new Intent(this, ServiceSinkhole.class);
        riWifi.putExtra(ServiceSinkhole.EXTRA_COMMAND, ServiceSinkhole.Command.set);
        riWifi.putExtra(ServiceSinkhole.EXTRA_NETWORK, "wifi");
        riWifi.putExtra(ServiceSinkhole.EXTRA_UID, uid);
        riWifi.putExtra(ServiceSinkhole.EXTRA_PACKAGE, packages[0]);
        riWifi.putExtra(ServiceSinkhole.EXTRA_BLOCKED, !wifi);

        PendingIntent piWifi = PendingIntent.getService(this, uid, riWifi, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action wAction = new NotificationCompat.Action.Builder(
                wifi ? R.drawable.wifi_on : R.drawable.wifi_off,
                getString(wifi ? R.string.title_allow_wifi : R.string.title_block_wifi),
                piWifi
        ).build();
        builder.addAction(wAction);

        // Build mobile action
        Intent riOther = new Intent(this, ServiceSinkhole.class);
        riOther.putExtra(ServiceSinkhole.EXTRA_COMMAND, ServiceSinkhole.Command.set);
        riOther.putExtra(ServiceSinkhole.EXTRA_NETWORK, "other");
        riOther.putExtra(ServiceSinkhole.EXTRA_UID, uid);
        riOther.putExtra(ServiceSinkhole.EXTRA_PACKAGE, packages[0]);
        riOther.putExtra(ServiceSinkhole.EXTRA_BLOCKED, !other);
        PendingIntent piOther = PendingIntent.getService(this, uid + 10000, riOther, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action oAction = new NotificationCompat.Action.Builder(
                other ? R.drawable.other_on : R.drawable.other_off,
                getString(other ? R.string.title_allow_other : R.string.title_block_other),
                piOther
        ).build();
        builder.addAction(oAction);

        // Show notification
        if (internet)
            NotificationManagerCompat.from(this).notify(uid, builder.build());
        else {
            NotificationCompat.BigTextStyle expanded = new NotificationCompat.BigTextStyle(builder);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
                expanded.bigText(getString(R.string.msg_installed_n));
            else
                expanded.bigText(getString(R.string.msg_installed, name));
            expanded.setSummaryText(getString(R.string.title_internet));
            NotificationManagerCompat.from(this).notify(uid, expanded.build());
        }

    } catch (PackageManager.NameNotFoundException ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
    }
}
 
Example 15
Source File: MainActivity.java    From wearable with Apache License 2.0 4 votes vote down vote up
/**
 * This one adds a button to the notification.  launches the camera for this example.
 */
void addbuttonNoti() {
    Log.i("main", "addbutton noti");
    //create the intent to launch the notiactivity, then the pentingintent.
    Intent viewIntent = new Intent(this, NotiActivity.class);
    viewIntent.putExtra("NotiID", "Notification ID is " + notificationID);

    PendingIntent viewPendingIntent =
        PendingIntent.getActivity(this, 0, viewIntent, 0);

    // we are going to add an intent to open the camera here.
    //Intent cameraIntent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    PendingIntent cameraPendingIntent =
        PendingIntent.getActivity(this, 0, cameraIntent, 0);

    NotificationCompat.Action.WearableExtender inlineActionForWear2 =
        new NotificationCompat.Action.WearableExtender()
            .setHintDisplayActionInline(true)
            .setHintLaunchesActivity(true);

    // Add an action to allow replies.
    NotificationCompat.Action pictureAction =
        new NotificationCompat.Action.Builder(
            R.drawable.ic_action_time,
            "Open Camera",
            cameraPendingIntent)
            .extend(inlineActionForWear2)
            .build();

    //Now create the notification.  We must use the NotificationCompat or it will not work on the wearable.
    NotificationCompat.Builder notificationBuilder =
        new NotificationCompat.Builder(this, id)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("add button Noti")
            .setContentText("Tap for full message.")
            .setContentIntent(viewPendingIntent)
            .setChannelId(id)
            .addAction(pictureAction);

    // Get an instance of the NotificationManager service
    NotificationManagerCompat notificationManager =
        NotificationManagerCompat.from(this);

    // Build the notification and issues it with notification manager.
    notificationManager.notify(notificationID, notificationBuilder.build());
    notificationID++;

}
 
Example 16
Source File: InstallService.java    From aptoide-client-v8 with GNU General Public License v3.0 4 votes vote down vote up
@NonNull private NotificationCompat.Action getPauseAction(String md5) {
  return getAction(cm.aptoide.pt.downloadmanager.R.drawable.media_pause,
      getString(cm.aptoide.pt.downloadmanager.R.string.pause_download),
      getPausePendingIntent(md5));
}
 
Example 17
Source File: BigTextIntentService.java    From user-interface-samples with Apache License 2.0 4 votes vote down vote up
private NotificationCompat.Builder recreateBuilderWithBigTextStyle() {

        // Main steps for building a BIG_TEXT_STYLE notification (for more detailed comments on
        // building this notification, check MainActivity.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. Retrieve Notification Channel for O and beyond devices (26+). We don't need to create
        //    the NotificationChannel, since it was created the first time this Notification was
        //    created.
        String notificationChannelId = bigTextStyleReminderAppData.getChannelId();

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


        // 3. Set up main Intent for notification
        Intent notifyIntent = new Intent(this, BigTextMainActivity.class);
        notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

        PendingIntent notifyPendingIntent =
                PendingIntent.getActivity(
                        this,
                        0,
                        notifyIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );


        // 4. 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();


        // 5. Build and issue the notification.

        // Notification Channel Id is ignored for Android pre O (26).
        NotificationCompat.Builder notificationCompatBuilder =
                new NotificationCompat.Builder(
                        getApplicationContext(), notificationChannelId);

        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))
                .setContentIntent(notifyPendingIntent)
                .setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorPrimary))
                .setCategory(Notification.CATEGORY_REMINDER)
                .setPriority(bigTextStyleReminderAppData.getPriority())
                .setVisibility(bigTextStyleReminderAppData.getChannelLockscreenVisibility())
                .addAction(snoozeAction)
                .addAction(dismissAction);

        return notificationCompatBuilder;
    }
 
Example 18
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 19
Source File: OdysseyNotificationManager.java    From odyssey with GNU General Public License v3.0 4 votes vote down vote up
public synchronized void updateNotification(TrackModel track, PlaybackService.PLAYSTATE state, MediaSessionCompat.Token mediaSessionToken) {
    mLastState = state;
    mLastToken = mediaSessionToken;
    if (track != null) {
        openChannel();
        mNotificationBuilder = new NotificationCompat.Builder(mContext, NOTIFICATION_CHANNEL_ID);

        // Open application intent
        Intent mainIntent = new Intent(mContext, OdysseySplashActivity.class);
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION);
        mainIntent.putExtra(OdysseyMainActivity.MAINACTIVITY_INTENT_EXTRA_REQUESTEDVIEW, OdysseyMainActivity.REQUESTEDVIEW.NOWPLAYING.ordinal());
        PendingIntent contentPendingIntent = PendingIntent.getActivity(mContext, NOTIFICATION_INTENT_OPENGUI, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mNotificationBuilder.setContentIntent(contentPendingIntent);

        // Set pendingintents
        // Previous song action
        Intent prevIntent = new Intent(PlaybackService.ACTION_PREVIOUS);
        PendingIntent prevPendingIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_PREVIOUS, prevIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action prevAction = new NotificationCompat.Action.Builder(R.drawable.ic_skip_previous_48dp, "Previous", prevPendingIntent).build();

        // Pause/Play action
        PendingIntent playPauseIntent;
        int playPauseIcon;
        if (state == PlaybackService.PLAYSTATE.PLAYING) {
            Intent pauseIntent = new Intent(PlaybackService.ACTION_PAUSE);
            playPauseIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_PLAYPAUSE, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            playPauseIcon = R.drawable.ic_pause_48dp;
        } else {
            Intent playIntent = new Intent(PlaybackService.ACTION_PLAY);
            playPauseIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_PLAYPAUSE, playIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            playPauseIcon = R.drawable.ic_play_arrow_48dp;
        }
        NotificationCompat.Action playPauseAction = new NotificationCompat.Action.Builder(playPauseIcon, "PlayPause", playPauseIntent).build();

        // Next song action
        Intent nextIntent = new Intent(PlaybackService.ACTION_NEXT);
        PendingIntent nextPendingIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_NEXT, nextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Action nextAction = new NotificationCompat.Action.Builder(R.drawable.ic_skip_next_48dp, "Next", nextPendingIntent).build();

        // Quit action
        Intent quitIntent = new Intent(PlaybackService.ACTION_QUIT);
        PendingIntent quitPendingIntent = PendingIntent.getBroadcast(mContext, NOTIFICATION_INTENT_QUIT, quitIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mNotificationBuilder.setDeleteIntent(quitPendingIntent);

        mNotificationBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        mNotificationBuilder.setSmallIcon(R.drawable.odyssey_notification);
        mNotificationBuilder.addAction(prevAction);
        mNotificationBuilder.addAction(playPauseAction);
        mNotificationBuilder.addAction(nextAction);
        androidx.media.app.NotificationCompat.MediaStyle notificationStyle = new androidx.media.app.NotificationCompat.MediaStyle();
        notificationStyle.setShowActionsInCompactView(1, 2);
        notificationStyle.setMediaSession(mediaSessionToken);
        mNotificationBuilder.setStyle(notificationStyle);
        mNotificationBuilder.setContentTitle(mContext.getResources().getString(R.string.notification_sensitive_content_replacement));

        // Remove unnecessary time info
        mNotificationBuilder.setShowWhen(false);

        //Build the public notification
        Notification notificationPublic = mNotificationBuilder.build();

        mNotificationBuilder.setContentTitle(track.getTrackDisplayedName());
        mNotificationBuilder.setContentText(track.getTrackArtistName());

        // Cover but only if changed
        if (mLastTrack == null || !track.getTrackAlbumKey().equals(mLastTrack.getTrackAlbumKey())) {
            mLastTrack = track;
            mLastBitmap = null;
        }

        // Only set image if an saved one is available
        if (mLastBitmap != null && !mHideArtwork) {
            mNotificationBuilder.setLargeIcon(mLastBitmap);
        }

        // Build the private notification
        if (mHideMediaOnLockscreen) {
            mNotificationBuilder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);
        }

        mNotification = mNotificationBuilder.build();
        mNotification.publicVersion = notificationPublic;

        // Check if run from service and check if playing or pause.
        // Pause notification should be dismissible.
        if (mContext instanceof Service) {
            if (state == PlaybackService.PLAYSTATE.PLAYING) {
                ((Service) mContext).startForeground(NOTIFICATION_ID, mNotification);
            } else {
                ((Service) mContext).stopForeground(false);
            }
        }

        // Send the notification away
        mNotificationManager.notify(NOTIFICATION_ID, mNotification);
    }

}
 
Example 20
Source File: QiscusPushNotificationUtil.java    From qiscus-sdk-android with Apache License 2.0 4 votes vote down vote up
private static void pushNotification(Context context, QiscusComment comment,
                                     QiscusPushNotificationMessage pushNotificationMessage, Bitmap largeIcon) {

    String notificationChannelId = Qiscus.getApps().getPackageName() + ".qiscus.sdk.notification.channel";
    if (BuildVersionUtil.isOreoOrHigher()) {
        NotificationChannel notificationChannel =
                new NotificationChannel(notificationChannelId, "Chat", NotificationManager.IMPORTANCE_HIGH);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (notificationManager != null) {
            notificationManager.createNotificationChannel(notificationChannel);
        }
    }

    PendingIntent pendingIntent;
    Intent openIntent = new Intent(context, QiscusPushNotificationClickReceiver.class);
    openIntent.putExtra("data", comment);
    pendingIntent = PendingIntent.getBroadcast(context, QiscusNumberUtil.convertToInt(comment.getRoomId()),
            openIntent, PendingIntent.FLAG_CANCEL_CURRENT);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, notificationChannelId);
    notificationBuilder.setContentTitle(pushNotificationMessage.getRoomName())
            .setContentIntent(pendingIntent)
            .setContentText(pushNotificationMessage.getMessage())
            .setTicker(pushNotificationMessage.getMessage())
            .setSmallIcon(Qiscus.getChatConfig().getNotificationSmallIcon())
            .setLargeIcon(largeIcon)
            .setColor(ContextCompat.getColor(context, Qiscus.getChatConfig().getInlineReplyColor()))
            .setGroup("CHAT_NOTIF_" + comment.getRoomId())
            .setAutoCancel(true)
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

    if (Qiscus.getChatConfig().isEnableReplyNotification() && isNougatOrHigher()) {
        String getRepliedTo = pushNotificationMessage.getRoomName();
        RemoteInput remoteInput = new RemoteInput.Builder(KEY_NOTIFICATION_REPLY)
                .setLabel(QiscusTextUtil.getString(R.string.qiscus_reply_to, getRepliedTo.toUpperCase()))
                .build();

        NotificationCompat.Action replyAction = new NotificationCompat.Action.Builder(android.R.drawable.ic_menu_send,
                QiscusTextUtil.getString(R.string.qiscus_reply_to, getRepliedTo.toUpperCase()), pendingIntent)
                .addRemoteInput(remoteInput)
                .build();
        notificationBuilder.addAction(replyAction);
    }

    boolean cancel = false;
    if (Qiscus.getChatConfig().getNotificationBuilderInterceptor() != null) {
        cancel = !Qiscus.getChatConfig().getNotificationBuilderInterceptor()
                .intercept(notificationBuilder, comment);
    }

    if (cancel) {
        return;
    }

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    List<QiscusPushNotificationMessage> notifItems = QiscusCacheManager.getInstance()
            .getMessageNotifItems(comment.getRoomId());
    if (notifItems == null) {
        notifItems = new ArrayList<>();
    }
    int notifSize = 5;
    if (notifItems.size() < notifSize) {
        notifSize = notifItems.size();
    }
    if (notifItems.size() > notifSize) {
        inboxStyle.addLine(".......");
    }
    int start = notifItems.size() - notifSize;
    for (int i = start; i < notifItems.size(); i++) {
        inboxStyle.addLine(notifItems.get(i).getMessage());
    }
    inboxStyle.setSummaryText(QiscusTextUtil.getString(R.string.qiscus_notif_count, notifItems.size()));
    notificationBuilder.setStyle(inboxStyle);

    if (notifSize <= 3) {
        notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
    }

    QiscusAndroidUtil.runOnUIThread(() -> NotificationManagerCompat.from(context)
            .notify(QiscusNumberUtil.convertToInt(comment.getRoomId()), notificationBuilder.build()));
}