Java Code Examples for androidx.core.app.NotificationManagerCompat#notify()

The following examples show how to use androidx.core.app.NotificationManagerCompat#notify() . 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: MobileCellsRegistrationService.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
private void showResultNotification() {
    String text = getString(R.string.mobile_cells_registration_pref_dlg_status_stopped);
    String newCount = getString(R.string.mobile_cells_registration_pref_dlg_status_new_cells_count);
    long iValue = DatabaseHandler.getInstance(getApplicationContext()).getNewMobileCellsCount();
    newCount = newCount + " " + iValue;
    text = text + "; " + newCount;
    if (android.os.Build.VERSION.SDK_INT < 24) {
        text = text+" ("+getString(R.string.ppp_app_name)+")";
    }

    PPApplication.createMobileCellsRegistrationNotificationChannel(this);
    NotificationCompat.Builder mBuilder =   new NotificationCompat.Builder(this, PPApplication.MOBILE_CELLS_REGISTRATION_NOTIFICATION_CHANNEL)
            .setColor(ContextCompat.getColor(this, R.color.notificationDecorationColor))
            .setSmallIcon(R.drawable.ic_exclamation_notify) // notification icon
            .setContentTitle(getString(R.string.phone_profiles_pref_applicationEventMobileCellsRegistration_notification)) // title for notification
            .setContentText(text) // message for notification
            .setAutoCancel(true); // clear notification after click

    //mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
    //if (android.os.Build.VERSION.SDK_INT >= 21)
    //{
        mBuilder.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION);
        mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
    //}

    Notification notification = mBuilder.build();
    NotificationManagerCompat mNotificationManager = NotificationManagerCompat.from(this);
    try {
        mNotificationManager.notify(
                PPApplication.MOBILE_CELLS_REGISTRATION_RESULT_NOTIFICATION_TAG,
                PPApplication.MOBILE_CELLS_REGISTRATION_RESULT_NOTIFICATION_ID, notification);
    } catch (Exception e) {
        //Log.e("MobileCellsRegistrationService.showResultNotification", Log.getStackTraceString(e));
        PPApplication.recordException(e);
    }
}
 
Example 2
Source File: NotificationHelper.java    From NekoSMS with GNU General Public License v3.0 5 votes vote down vote up
public static void displayNotification(Context context, Uri messageUri) {
    if (!areNotificationsEnabled(context)) {
        BlockedSmsLoader.get().setSeenStatus(context, messageUri, true);
        return;
    }

    SmsMessageData messageData = BlockedSmsLoader.get().query(context, messageUri);
    Notification notification = buildNotificationSingle(context, messageData);
    applyNotificationStyle(context, notification);

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
    notificationManager.notify(uriToNotificationId(messageUri), notification);
}
 
Example 3
Source File: ImportantInfoNotification.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
static private void showNotification(Context context,
                                     @SuppressWarnings("SameParameterValue") boolean firstInstallation,
                                     String title, String text) {
    String nTitle = title;
    String nText = text;
    if (android.os.Build.VERSION.SDK_INT < 24) {
        nTitle = context.getString(R.string.ppp_app_name);
        nText = title+": "+text;
    }
    PPApplication.createExclamationNotificationChannel(context);
    NotificationCompat.Builder mBuilder =   new NotificationCompat.Builder(context, PPApplication.EXCLAMATION_NOTIFICATION_CHANNEL)
            .setColor(ContextCompat.getColor(context, R.color.notificationDecorationColor))
            .setSmallIcon(R.drawable.ic_exclamation_notify) // notification icon
            .setContentTitle(nTitle) // title for notification
            .setContentText(nText) // message for notification
            .setAutoCancel(true); // clear notification after click
    mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(nText));
    Intent intent = new Intent(context, ImportantInfoActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(EXTRA_FIRST_INSTALLATION, firstInstallation);
    PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(pi);
    mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
    //if (android.os.Build.VERSION.SDK_INT >= 21)
    //{
        mBuilder.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION);
        mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
    //}
    NotificationManagerCompat mNotificationManager = NotificationManagerCompat.from(context);
    try {
        mNotificationManager.notify(
                PPApplication.IMPORTANT_INFO_NOTIFICATION_TAG,
                PPApplication.IMPORTANT_INFO_NOTIFICATION_ID, mBuilder.build());
    } catch (Exception e) {
        //Log.e("ImportantInfoNotification.showNotification", Log.getStackTraceString(e));
        PPApplication.recordException(e);
    }
}
 
Example 4
Source File: NotificationService.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
public void notify(int id, Notification notification) {
    final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
    try {
        notificationManager.notify(id, notification);
    } catch (RuntimeException e) {
        Log.d(Config.LOGTAG, "unable to make notification", e);
    }
}
 
Example 5
Source File: DrawOverAppsPermissionNotification.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
static private void showNotification(Context context, String title, String text) {
    PPApplication.createExclamationNotificationChannel(context);
    NotificationCompat.Builder mBuilder =   new NotificationCompat.Builder(context, PPApplication.EXCLAMATION_NOTIFICATION_CHANNEL)
            .setColor(ContextCompat.getColor(context, R.color.notificationDecorationColor))
            .setSmallIcon(R.drawable.ic_exclamation_notify) // notification icon
            .setContentTitle(title) // title for notification
            .setContentText(text) // message for notification
            .setAutoCancel(true); // clear notification after click
    mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(text));
    final Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
    intent.setData(Uri.parse("package:" + context.getPackageName()));
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(pi);
    mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
    //if (android.os.Build.VERSION.SDK_INT >= 21)
    //{
        mBuilder.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION);
        mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
    //}
    mBuilder.setOnlyAlertOnce(true);

    NotificationManagerCompat mNotificationManager = NotificationManagerCompat.from(context);
    try {
        mNotificationManager.notify(
                PPApplication.DRAW_OVER_APPS_NOTIFICATION_TAG,
                PPApplication.DRAW_OVER_APPS_NOTIFICATION_ID, mBuilder.build());
    } catch (Exception e) {
        //Log.e("DrawOverAppsPermissionNotification.showNotification", Log.getStackTraceString(e));
        PPApplication.recordException(e);
    }
}
 
Example 6
Source File: GeofencesScanner.java    From PhoneProfilesPlus with Apache License 2.0 5 votes vote down vote up
private void showErrorNotification(int errorCode) {
    String nTitle = context.getString(R.string.event_preferences_location_google_api_connection_error_title);
    String nText = context.getString(R.string.event_preferences_location_google_api_connection_error_text);
    if (android.os.Build.VERSION.SDK_INT < 24) {
        nTitle = context.getString(R.string.ppp_app_name);
        nText = context.getString(R.string.event_preferences_location_google_api_connection_error_title)+": "+
                context.getString(R.string.event_preferences_location_google_api_connection_error_text);
    }
    PPApplication.createExclamationNotificationChannel(context);
    NotificationCompat.Builder mBuilder =   new NotificationCompat.Builder(context, PPApplication.EXCLAMATION_NOTIFICATION_CHANNEL)
            .setColor(ContextCompat.getColor(context, R.color.notificationDecorationColor))
            .setSmallIcon(R.drawable.ic_exclamation_notify) // notification icon
            .setContentTitle(nTitle) // title for notification
            .setContentText(nText) // message for notification
            .setAutoCancel(true); // clear notification after click
    mBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(nText));
    Intent intent = new Intent(context, GeofenceScannerErrorActivity.class);
    intent.putExtra(DIALOG_ERROR, errorCode);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pi = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(pi);
    mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
    //if (android.os.Build.VERSION.SDK_INT >= 21)
    //{
        mBuilder.setCategory(NotificationCompat.CATEGORY_RECOMMENDATION);
        mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
    //}
    NotificationManagerCompat mNotificationManager = NotificationManagerCompat.from(context);
    try {
        mNotificationManager.notify(
                PPApplication.GEOFENCE_SCANNER_ERROR_NOTIFICATION_TAG,
                PPApplication.GEOFENCE_SCANNER_ERROR_NOTIFICATION_ID, mBuilder.build());
    } catch (Exception e) {
        //Log.e("GeofencesScanner.showErrorNotification", Log.getStackTraceString(e));
        PPApplication.recordException(e);
    }
}
 
Example 7
Source File: AppStatesService.java    From android-testdpc with Apache License 2.0 5 votes vote down vote up
private void showNotification(ReceivedKeyedAppState state, boolean requestSync) {
  final String logMessage = state.getTimestamp() + " " +
      state.getPackageName() + ":" +
      state.getKey() + "=" +
      state.getData() + " (" +
      state.getMessage() + ")" + (requestSync ? " - SYNC REQUESTED" : "");

  if (state.getSeverity() == KeyedAppState.SEVERITY_ERROR) {
    Log.e(TAG, logMessage);
  } else {
    Log.i(TAG, logMessage);
  }

  final String severity = (state.getSeverity() == KeyedAppState.SEVERITY_ERROR) ? "ERROR" :
      (state.getSeverity() == KeyedAppState.SEVERITY_INFO) ? "INFO" : "UNKNOWN";

  NotificationCompat.Builder notificationBuilder =
      new NotificationCompat.Builder(this, CHANNEL_ID)
          .setSmallIcon(R.drawable.arrow_down)
          .setContentTitle(state.getPackageName() + ":" + state.getKey() + " " + severity)
          .setContentText(state.getTimestamp() + " " +
              state.getData() +
              " (" + state.getMessage() +")" +
              (requestSync ? "\nSYNC REQUESTED" : ""));
  NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
  notificationManager.notify(getIdForState(state), notificationBuilder.build());
}
 
Example 8
Source File: NotificationService.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
private void notify(String tag, int id, Notification notification) {
    final NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mXmppConnectionService);
    try {
        notificationManager.notify(tag, id, notification);
    } catch (RuntimeException e) {
        Log.d(Config.LOGTAG, "unable to make notification", e);
    }
}
 
Example 9
Source File: NotificationHelper.java    From MaxLock with GNU General Public License v3.0 5 votes vote down vote up
public static void postIModNotification(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        createNotificationChannels(context);
    }

    NotificationManagerCompat nm = NotificationManagerCompat.from(context);
    if (!MLPreferences.getPrefsApps(context).getBoolean(Common.SHOW_RESET_RELOCK_TIMER_NOTIFICATION, false)) {
        nm.cancel(IMOD_NOTIFICATION_ID);
        return;
    }
    Intent notifyIntent = new Intent(context, ActionActivity.class);
    notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notifyIntent.putExtra(ActionsHelper.ACTION_EXTRA_KEY, ActionsHelper.ACTION_IMOD_RESET);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, IMOD_CHANNEL)
            .setContentTitle(context.getString(R.string.action_imod_reset))
            .setContentText("")
            .setSmallIcon(R.drawable.ic_apps_24dp)
            .setContentIntent(PendingIntent.getActivity(context.getApplicationContext(), 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT))
            .setOngoing(true)
            .setAutoCancel(true)
            .setShowWhen(false)
            .setPriority(NotificationCompat.PRIORITY_MIN)
            .setCategory(NotificationCompat.CATEGORY_STATUS)
            .setColor(ContextCompat.getColor(context, R.color.accent));
    nm.notify(IMOD_NOTIFICATION_ID, builder.build());
}
 
Example 10
Source File: ListenerService.java    From AndroidAPS with GNU Affero General Public License v3.0 5 votes vote down vote up
private void showBolusProgress(int progresspercent, String progresstatus) {
    Intent cancelIntent = new Intent(this, ListenerService.class);
    cancelIntent.setAction(ACTION_CANCELBOLUS);
    PendingIntent cancelPendingIntent = PendingIntent.getService(this, 0, cancelIntent, 0);

    long[] vibratePattern;
    boolean vibreate = PreferenceManager
            .getDefaultSharedPreferences(this).getBoolean("vibrateOnBolus", true);
    if(vibreate){
        vibratePattern = new long[]{0, 50, 1000};
    } else {
        vibratePattern = new long[]{0, 1, 1000};
    }

    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.ic_icon)
                    .setContentTitle("Bolus Progress")
                    .setContentText(progresspercent + "% - " + progresstatus)
                    .setContentIntent(cancelPendingIntent)
                    .setPriority(NotificationCompat.PRIORITY_MAX)
                    .setVibrate(vibratePattern)
                    .addAction(R.drawable.ic_cancel, "CANCEL BOLUS", cancelPendingIntent);

    NotificationManagerCompat notificationManager =
            NotificationManagerCompat.from(this);

    if(confirmThread != null){
        confirmThread.invalidate();
    }
    notificationManager.notify(BOLUS_PROGRESS_NOTIF_ID, notificationBuilder.build());
    notificationManager.cancel(CONFIRM_NOTIF_ID); // multiple watch setup


    if (progresspercent == 100){
        scheduleDismissBolusprogress(5);
    }
}
 
Example 11
Source File: WearableNotificationWithVoice.java    From Applozic-Android-SDK with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * This method is just like a wrapper class method for usual notification class which add voice actions
 * for wearable devices
 *
 * @throws RuntimeException
 */
public void sendNotification() throws Exception {
    if (pendingIntent == null && notificationHandler == null) {
        throw new RuntimeException("Either pendingIntent or handler class requires.");
    }
    //Action action = buildWearableAction(); removed remote input action for now
    Notification notification = notificationBuilder.extend(new WearableExtender()).build();

    if (ApplozicClient.getInstance(mContext).isNotificationSmallIconHidden() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        int smallIconViewId = mContext.getResources().getIdentifier("right_icon", "id", android.R.class.getPackage().getName());
        if (smallIconViewId != 0) {

            if (notification.contentIntent != null  && notification.contentView != null) {
                notification.contentView.setViewVisibility(smallIconViewId, View.INVISIBLE);
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if (notification.headsUpContentView != null) {
                    notification.headsUpContentView.setViewVisibility(smallIconViewId, View.INVISIBLE);
                }
                if (notification.bigContentView != null) {
                    notification.bigContentView.setViewVisibility(smallIconViewId, View.INVISIBLE);
                }
            }

        }
    }
    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(mContext);
    notificationManager.notify(notificationId, notification);
}
 
Example 12
Source File: NoticationService.java    From zone-sdk with MIT License 4 votes vote down vote up
private void notifyABC() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String mylib_channel = "Mylib_channel";

            NotificationChannel chan1 = new NotificationChannel(mylib_channel, "Mylib", NotificationManager.IMPORTANCE_HIGH);

            chan1.setLightColor(Color.CYAN);
            chan1.setLockscreenVisibility(NotificationCompat.VISIBILITY_PRIVATE);
//            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(chan1);
            ((NotificationManager) getSystemService(NotificationManager.class)).createNotificationChannel(chan1);


            NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), mylib_channel);
            builder.setContentTitle("title")
                    .setContentText("content")
                    .setSmallIcon(R.drawable.icon)
                    .setColor(ContextCompat.getColor(this, R.color.colorAccent))
                    .setAutoCancel(true)

                    //浮动通知 设置
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setPriority(NotificationCompat.PRIORITY_HIGH);


            //加上跳转
            Intent intent2 = new Intent(this, MainActivity2.class);
            intent2.setAction("android.intent2.action.MAIN");
            intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent2.addCategory("android.intent2.category.LAUNCHER");
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent2, 0);
            builder.setContentIntent(pendingIntent);


            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
            HandlerUiUtil.INSTANCE.postDelayed(new Runnable() {
                @Override
                public void run() {
                    //不加也是好用的
                    notificationManager.cancel(0);
                }
            }, 2000);

            //浮动通知 设置
            notificationManager.notify(0, builder.build());

//            this.startForeground(244, builder.build());
        }
    }
 
Example 13
Source File: MessagingIntentService.java    From wear-os-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(NotificationsActivity.NOTIFICATION_ID, notification);
    }
}
 
Example 14
Source File: OngoingCallActivity.java    From call_manage with MIT License 4 votes vote down vote up
private void createNotification() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Contact callerContact = CallManager.getDisplayContact(this);
            String callerName = callerContact.getName();

            Intent touchNotification = new Intent(this, OngoingCallActivity.class);
            touchNotification.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, touchNotification, 0);

            // Answer Button Intent
            Intent answerIntent = new Intent(this, NotificationActionReceiver.class);
            answerIntent.setAction(ACTION_ANSWER);
            answerIntent.putExtra(EXTRA_NOTIFICATION_ID, 0);
            PendingIntent answerPendingIntent = PendingIntent.getBroadcast(this, 0, answerIntent, PendingIntent.FLAG_CANCEL_CURRENT);

            // Hangup Button Intent
            Intent hangupIntent = new Intent(this, NotificationActionReceiver.class);
            hangupIntent.setAction(ACTION_HANGUP);
            hangupIntent.putExtra(EXTRA_NOTIFICATION_ID, 0);
            PendingIntent hangupPendingIntent = PendingIntent.getBroadcast(this, 1, hangupIntent, PendingIntent.FLAG_CANCEL_CURRENT);

            mBuilder = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setSmallIcon(R.drawable.icon_full_144)
                    .setContentTitle(callerName)
                    .setContentText(mStateText)
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setContentIntent(pendingIntent)
                    .setColor(ThemeUtils.getAccentColor(this))
                    .setOngoing(true)
                    .setStyle(new androidx.media.app.NotificationCompat.MediaStyle().setShowActionsInCompactView(0, 1))
                    .setAutoCancel(true);

            // Adding the action buttons
            mBuilder.addAction(R.drawable.ic_call_black_24dp, getString(R.string.action_answer), answerPendingIntent);
            mBuilder.addAction(R.drawable.ic_call_end_black_24dp, getString(R.string.action_hangup), hangupPendingIntent);

            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
            notificationManager.notify(NOTIFICATION_ID, mBuilder.build());
        }
    }
 
Example 15
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 16
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(MainActivity.NOTIFICATION_ID, notification);
    }
}
 
Example 17
Source File: BigPictureSocialIntentService.java    From user-interface-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Handles action for adding a comment from the notification.
 */
private void handleActionComment(CharSequence comment) {
    Log.d(TAG, "handleActionComment(): " + comment);

    if (comment != 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 comment from the user
         *  regarding the post (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 = recreateBuilderWithBigPictureStyle();
        }

        // Updates active Notification
        Notification updatedNotification = notificationCompatBuilder
                // Adds a line and comment below content in Notification
                .setRemoteInputHistory(new CharSequence[]{comment})
                .build();

        // Pushes out the updated Notification
        NotificationManagerCompat notificationManagerCompat =
                NotificationManagerCompat.from(getApplicationContext());
        notificationManagerCompat.notify(MainActivity.NOTIFICATION_ID, updatedNotification);
    }
}
 
Example 18
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 19
Source File: MainActivity.java    From wearable with Apache License 2.0 4 votes vote down vote up
/**
 * This adds the voice response for the wearable device.
 * It comes back via an intent, which is shown in voiceNotiActivity.
 */
void voiceReplytNoti() {


    //create the intent to launch the notiactivity, then the pentingintent.
    Intent replyIntent = new Intent(this, VoiceNotiActivity.class);
    replyIntent.putExtra("NotiID", "Notification ID is " + notificationID);

    PendingIntent replyPendingIntent =
        PendingIntent.getActivity(this, 0, replyIntent, 0);

    // create the remote input part for the notification.
    RemoteInput remoteInput = new RemoteInput.Builder(EXTRA_VOICE_REPLY)
        .setLabel("Reply")
        .build();


    // Create the reply action and add the remote input
    NotificationCompat.Action action =
        new NotificationCompat.Action.Builder(R.drawable.ic_action_map,
            "Reply", replyPendingIntent)
            .addRemoteInput(remoteInput)
            .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("reply Noti")
            .setContentText("voice reply example.")
            .setChannelId(id)
            .extend(new WearableExtender().addAction(action));

    // 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 20
Source File: NotificationManager.java    From Hentoid with Apache License 2.0 4 votes vote down vote up
public void notify(@NonNull Notification notification) {
    NotificationManagerCompat managerCompat = NotificationManagerCompat.from(context);
    managerCompat.notify(notificationId, notification.onCreateNotification(context));
}