Example usage for android.app NotificationChannel NotificationChannel

List of usage examples for android.app NotificationChannel NotificationChannel

Introduction

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

Prototype

public NotificationChannel(String id, CharSequence name, @Importance int importance) 

Source Link

Document

Creates a notification channel.

Usage

From source file:com.irccloud.android.data.collection.NotificationsList.java

@SuppressLint("NewApi")
private android.app.Notification buildNotification(String ticker, int cid, int bid, long[] eids, String title,
        String text, int count, Intent replyIntent, String network, ArrayList<Notification> messages,
        NotificationCompat.Action otherAction, Bitmap largeIcon, Bitmap wearBackground) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel c = new NotificationChannel(String.valueOf(bid), title,
                NotificationManager.IMPORTANCE_HIGH);
        c.setGroup(String.valueOf(cid));
        ((NotificationManager) IRCCloudApplication.getInstance().getApplicationContext()
                .getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(c);
    }//w w  w  .  j a  v  a2  s. c  o  m
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
    int defaults = 0;
    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            IRCCloudApplication.getInstance().getApplicationContext(), String.valueOf(bid))
                    .setContentTitle(
                            title + ((network != null && !network.equals(title)) ? (" (" + network + ")") : ""))
                    .setContentText(Html.fromHtml(text)).setAutoCancel(true).setTicker(ticker)
                    .setWhen(eids[0] / 1000).setSmallIcon(R.drawable.ic_stat_notify).setLargeIcon(largeIcon)
                    .setColor(IRCCloudApplication.getInstance().getApplicationContext().getResources()
                            .getColor(R.color.ic_background))
                    .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
                    .setCategory(NotificationCompat.CATEGORY_MESSAGE)
                    .setPriority(hasTouchWiz() ? NotificationCompat.PRIORITY_DEFAULT
                            : NotificationCompat.PRIORITY_HIGH)
                    .setOnlyAlertOnce(false);

    if (ticker != null && (System.currentTimeMillis() - prefs.getLong("lastNotificationTime", 0)) > 2000) {
        String ringtone = prefs.getString("notify_ringtone",
                "android.resource://"
                        + IRCCloudApplication.getInstance().getApplicationContext().getPackageName() + "/"
                        + R.raw.digit);
        if (ringtone.length() > 0)
            builder.setSound(Uri.parse(ringtone));
    }

    int led_color = Integer.parseInt(prefs.getString("notify_led_color", "1"));
    if (led_color == 1) {
        defaults = android.app.Notification.DEFAULT_LIGHTS;
    } else if (led_color == 2) {
        builder.setLights(0xFF0000FF, 500, 500);
    }

    if (prefs.getBoolean("notify_vibrate", true) && ticker != null
            && (System.currentTimeMillis() - prefs.getLong("lastNotificationTime", 0)) > 2000)
        defaults |= android.app.Notification.DEFAULT_VIBRATE;
    else
        builder.setVibrate(new long[] { 0L });

    builder.setDefaults(defaults);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putLong("lastNotificationTime", System.currentTimeMillis());
    editor.commit();

    Intent i = new Intent();
    i.setComponent(new ComponentName(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
            "com.irccloud.android.MainActivity"));
    i.putExtra("bid", bid);
    i.setData(Uri.parse("bid://" + bid));
    Intent dismiss = new Intent(IRCCloudApplication.getInstance().getApplicationContext().getResources()
            .getString(R.string.DISMISS_NOTIFICATION));
    dismiss.setData(Uri.parse("irccloud-dismiss://" + bid));
    dismiss.putExtra("bid", bid);
    dismiss.putExtra("eids", eids);

    PendingIntent dismissPendingIntent = PendingIntent.getBroadcast(
            IRCCloudApplication.getInstance().getApplicationContext(), 0, dismiss,
            PendingIntent.FLAG_UPDATE_CURRENT);

    builder.setContentIntent(
            PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                    PendingIntent.FLAG_UPDATE_CURRENT));
    builder.setDeleteIntent(dismissPendingIntent);

    WearableExtender wearableExtender = new WearableExtender();
    wearableExtender.setBackground(wearBackground);
    if (messages != null && messages.size() > 0) {
        StringBuilder weartext = new StringBuilder();
        String servernick = getServerNick(messages.get(0).cid);
        NotificationCompat.MessagingStyle style = new NotificationCompat.MessagingStyle(servernick);
        style.setConversationTitle(title + ((network != null) ? (" (" + network + ")") : ""));
        for (Notification n : messages) {
            if (n != null && n.message != null && n.message.length() > 0) {
                if (weartext.length() > 0)
                    weartext.append("<br/>");
                if (n.message_type.equals("buffer_me_msg")) {
                    style.addMessage(Html.fromHtml(n.message).toString(), n.eid / 1000,
                            " " + ((n.nick == null) ? servernick : n.nick));
                    weartext.append("<b> ").append((n.nick == null) ? servernick : n.nick).append("</b> ")
                            .append(n.message);
                } else {
                    style.addMessage(Html.fromHtml(n.message).toString(), n.eid / 1000, n.nick);
                    weartext.append("<b>&lt;").append((n.nick == null) ? servernick : n.nick)
                            .append("&gt;</b> ").append(n.message);
                }
            }
        }

        ArrayList<String> history = new ArrayList<>(messages.size());
        for (int j = messages.size() - 1; j >= 0; j--) {
            Notification n = messages.get(j);
            if (n != null) {
                if (n.nick == null)
                    history.add(Html.fromHtml(n.message).toString());
                else
                    break;
            }
        }
        builder.setRemoteInputHistory(history.toArray(new String[history.size()]));
        builder.setStyle(style);

        if (messages.size() > 1) {
            wearableExtender.addPage(
                    new NotificationCompat.Builder(IRCCloudApplication.getInstance().getApplicationContext())
                            .setContentText(Html.fromHtml(weartext.toString()))
                            .extend(new WearableExtender().setStartScrollBottom(true)).build());
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN
                && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
            weartext.setLength(0);
            int j = 0;
            for (Notification n : messages) {
                if (messages.size() - ++j < 3) {
                    if (n != null && n.message != null && n.message.length() > 0) {
                        if (weartext.length() > 0)
                            weartext.append("<br/>");
                        if (n.message_type.equals("buffer_me_msg")) {
                            weartext.append("<b> ").append((n.nick == null) ? servernick : n.nick)
                                    .append("</b> ").append(n.message);
                        } else {
                            weartext.append("<b>&lt;").append((n.nick == null) ? servernick : n.nick)
                                    .append("&gt;</b> ").append(n.message);
                        }
                    }
                }
            }

            RemoteViews bigContentView = new RemoteViews(
                    IRCCloudApplication.getInstance().getApplicationContext().getPackageName(),
                    R.layout.notification_expanded);
            bigContentView.setTextViewText(R.id.title,
                    title + (!title.equals(network) ? (" (" + network + ")") : ""));
            bigContentView.setTextViewText(R.id.text, Html.fromHtml(weartext.toString()));
            bigContentView.setImageViewBitmap(R.id.image, largeIcon);
            bigContentView.setLong(R.id.time, "setTime", eids[0] / 1000);
            if (count > 3) {
                bigContentView.setViewVisibility(R.id.more, View.VISIBLE);
                bigContentView.setTextViewText(R.id.more, "+" + (count - 3) + " more");
            } else {
                bigContentView.setViewVisibility(R.id.more, View.GONE);
            }
            if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)) {
                bigContentView.setViewVisibility(R.id.actions, View.VISIBLE);
                bigContentView.setViewVisibility(R.id.action_divider, View.VISIBLE);
                i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(),
                        QuickReplyActivity.class);
                i.setData(Uri.parse("irccloud-bid://" + bid));
                i.putExtras(replyIntent);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                PendingIntent quickReplyIntent = PendingIntent.getActivity(
                        IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                bigContentView.setOnClickPendingIntent(R.id.action_reply, quickReplyIntent);
            }
            builder.setCustomBigContentView(bigContentView);
        }
    }

    if (replyIntent != null) {
        PendingIntent replyPendingIntent = PendingIntent.getService(
                IRCCloudApplication.getInstance().getApplicationContext(), bid + 1, replyIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            builder.addAction(new NotificationCompat.Action.Builder(0, "Reply", replyPendingIntent)
                    .setAllowGeneratedReplies(true)
                    .addRemoteInput(
                            new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build())
                    .build());
        }

        NotificationCompat.Action.Builder actionBuilder = new NotificationCompat.Action.Builder(
                R.drawable.ic_wearable_reply, "Reply", replyPendingIntent).setAllowGeneratedReplies(true)
                        .addRemoteInput(
                                new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build());

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

        wearableExtender.addAction(actionBuilder.extend(actionExtender).build());

        NotificationCompat.CarExtender.UnreadConversation.Builder unreadConvBuilder = new NotificationCompat.CarExtender.UnreadConversation.Builder(
                title + ((network != null) ? (" (" + network + ")") : ""))
                        .setReadPendingIntent(dismissPendingIntent).setReplyAction(replyPendingIntent,
                                new RemoteInput.Builder("extra_reply").setLabel("Reply to " + title).build());

        if (messages != null) {
            for (Notification n : messages) {
                if (n != null && n.nick != null && n.message != null && n.message.length() > 0) {
                    if (n.buffer_type.equals("conversation")) {
                        if (n.message_type.equals("buffer_me_msg"))
                            unreadConvBuilder
                                    .addMessage(" " + n.nick + " " + Html.fromHtml(n.message).toString());
                        else
                            unreadConvBuilder.addMessage(Html.fromHtml(n.message).toString());
                    } else {
                        if (n.message_type.equals("buffer_me_msg"))
                            unreadConvBuilder
                                    .addMessage(" " + n.nick + " " + Html.fromHtml(n.message).toString());
                        else
                            unreadConvBuilder
                                    .addMessage(n.nick + " said: " + Html.fromHtml(n.message).toString());
                    }
                }
            }
        } else {
            unreadConvBuilder.addMessage(text);
        }
        unreadConvBuilder.setLatestTimestamp(eids[count - 1] / 1000);

        builder.extend(new NotificationCompat.CarExtender().setUnreadConversation(unreadConvBuilder.build()));
    }

    if (replyIntent != null && prefs.getBoolean("notify_quickreply", true)
            && Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
        i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class);
        i.setData(Uri.parse("irccloud-bid://" + bid));
        i.putExtras(replyIntent);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent quickReplyIntent = PendingIntent.getActivity(
                IRCCloudApplication.getInstance().getApplicationContext(), 0, i,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.addAction(R.drawable.ic_action_reply, "Quick Reply", quickReplyIntent);
    }

    if (otherAction != null) {
        int drawable = 0;
        if (otherAction.getIcon() == R.drawable.ic_wearable_add)
            drawable = R.drawable.ic_action_add;
        else if (otherAction.getIcon() == R.drawable.ic_wearable_reply)
            drawable = R.drawable.ic_action_reply;
        builder.addAction(
                new NotificationCompat.Action(drawable, otherAction.getTitle(), otherAction.getActionIntent()));
        wearableExtender.addAction(otherAction);
    }

    builder.extend(wearableExtender);

    return builder.build();
}

From source file:com.z3r0byte.magistify.Services.BackgroundService.java

private void newScheduleChangeNotification() {
    if (allowDataTransfer()) {
        Magister magister = GlobalAccount.MAGISTER;
        if (magister == null || magister.isExpired()) {
            Log.d(TAG, "ScheduleChangeNotification: No valid Magister");
        } else {//from   w  ww .j  a v a2s  . c o m

            AppointmentHandler appointmentHandler = new AppointmentHandler(magister);
            Appointment[] appointments;
            try {
                Log.d(TAG, "ScheduleChangeNotification: Requesting schedule changes....");
                appointments = appointmentHandler.getScheduleChanges(DateUtils.getToday(),
                        DateUtils.addDays(DateUtils.getToday(), 3));
            } catch (IOException | AssertionError e) {
                Log.d(TAG, "ScheduleChangeNotification: Error while requesting schedule changes");
                e.printStackTrace();
                return;
            }

            Boolean newChanges = false;
            if (appointments == null || appointments.length < 1) {
                return;
            } else {
                Log.d(TAG, "ScheduleChangeNotification: Checking for new changes....");
                for (Appointment appointment : appointments) {
                    if (!scheduleChangeDB.isInDatabase(appointment)) {
                        newChanges = true;
                    }
                }
                scheduleChangeDB.addItems(appointments);
            }

            if (newChanges) {
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
                mBuilder.setSmallIcon(R.drawable.ic_schedule_change);

                mBuilder.setContentTitle("Nieuwe roosterijziging(en)!");
                mBuilder.setContentText("Tik om te bekijken");
                mBuilder.setAutoCancel(true);
                mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
                mBuilder.setDefaults(Notification.DEFAULT_ALL);

                Intent resultIntent = new Intent(context, ScheduleChangeActivity.class);
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
                stackBuilder.addParentStack(ScheduleChangeActivity.class);
                stackBuilder.addNextIntent(resultIntent);
                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                mBuilder.setContentIntent(resultPendingIntent);

                NotificationManager mNotificationManager = (NotificationManager) context
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                if (Build.VERSION.SDK_INT >= 26) {
                    String channelId = NEW_SCHEDULE_CHANGE_NOTIFICATIONCHANNEL_ID;
                    CharSequence channelName = NEW_SCHEDULE_CHANGE_NOTIFICATIONCHANNEL_ID;
                    int importance = NotificationManager.IMPORTANCE_LOW;
                    NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName,
                            importance);
                    notificationChannel.enableLights(true);
                    notificationChannel.setLightColor(Color.RED);
                    notificationChannel.enableVibration(true);
                    notificationChannel.setImportance(NotificationManager.IMPORTANCE_DEFAULT);
                    notificationChannel.setVibrationPattern(new long[] { 100, 200, 150 });
                    mNotificationManager.createNotificationChannel(notificationChannel);
                    mBuilder.setChannelId(NEW_SCHEDULE_CHANGE_NOTIFICATIONCHANNEL_ID);
                }
                mNotificationManager.notify(NEW_SCHEDULE_CHANGE_NOTIFICATION_ID, mBuilder.build());
            }
        }

    }
}

From source file:com.z3r0byte.magistify.Services.BackgroundService.java

private void nextAppointmentChangedNotification() {
    Appointment[] appointments = scheduleChangeDB.getNotificationAppointments();
    String previousChangedAppointment = configUtil.getString("previous_changed_appointment");
    if (appointments.length > 0) {
        Appointment appointment = appointments[0];
        if (!appointment.startDateString.equals(previousChangedAppointment)) {
            String content;/*from w w  w.j  a v  a  2s .co m*/
            if (appointment.description != null && !appointment.description.equalsIgnoreCase("null")) {
                content = appointment.description;
            } else {
                content = "De les is uitgevallen!";
            }

            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
            mBuilder.setSmallIcon(R.drawable.ic_schedule_change);

            mBuilder.setContentTitle("Let op! De volgende les is gewijzigd!");
            mBuilder.setContentText(content);
            mBuilder.setAutoCancel(true);
            mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
            mBuilder.setDefaults(Notification.DEFAULT_ALL);

            Intent resultIntent = new Intent(context, ScheduleChangeActivity.class);
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
            stackBuilder.addParentStack(ScheduleChangeActivity.class);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            mBuilder.setContentIntent(resultPendingIntent);

            NotificationManager mNotificationManager = (NotificationManager) context
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            if (Build.VERSION.SDK_INT >= 26) {
                String channelId = NEXT_APPOINTMENT_CHANGED_NOTIFICATIONCHANNEL_ID;
                CharSequence channelName = NEXT_APPOINTMENT_CHANGED_NOTIFICATIONCHANNEL_ID;
                int importance = NotificationManager.IMPORTANCE_LOW;
                NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName,
                        importance);
                notificationChannel.enableLights(true);
                notificationChannel.setLightColor(Color.RED);
                notificationChannel.enableVibration(true);
                notificationChannel.setImportance(NotificationManager.IMPORTANCE_DEFAULT);
                notificationChannel.setVibrationPattern(new long[] { 100, 200, 150 });
                mNotificationManager.createNotificationChannel(notificationChannel);
                mBuilder.setChannelId(NEXT_APPOINTMENT_CHANGED_NOTIFICATIONCHANNEL_ID);
            }
            mNotificationManager.notify(NEXT_APPOINTMENT_CHANGED_NOTIFICATION_ID, mBuilder.build());

            configUtil.setString("previous_changed_appointment", appointment.startDateString);
        }
    } else {
        NotificationManager notifManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notifManager.cancel(NEXT_APPOINTMENT_CHANGED_NOTIFICATION_ID);
    }
}

From source file:com.z3r0byte.magistify.Services.BackgroundService.java

private void newHomeworkNotification() {
    Appointment[] newhomework = homeworkDB.getAppointmentsWithHomework();
    ArrayList<Appointment> homeworkList = new ArrayList<>();
    for (Appointment appointment : newhomework) {
        if (homeworkDB.isModified(appointment, true))
            homeworkList.add(appointment);
    }//from   ww  w. j a  va  2 s  .  co m
    Log.d(TAG, "newHomeworkNotification: Amount of new homework: " + homeworkList.size());
    if (homeworkList.size() > 0) {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
        mBuilder.setSmallIcon(R.drawable.ic_new_homework);

        String content = "Je hebt nieuw of aangepast huiswerk voor:";
        for (Appointment appointment : homeworkList) {
            content = content + "\n" + appointment.description
                    + DateUtils.formatDate(appointment.startDate, "' ('dd MMM')'");
        }

        mBuilder.setContentTitle("Nieuw huiswerk");
        mBuilder.setStyle(new NotificationCompat.BigTextStyle(mBuilder).bigText(content));
        mBuilder.setContentText(content);
        mBuilder.setAutoCancel(true);
        mBuilder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        mBuilder.setDefaults(Notification.DEFAULT_ALL);

        Intent resultIntent = new Intent(context, HomeworkActivity.class);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
        stackBuilder.addParentStack(ScheduleChangeActivity.class);
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        mBuilder.setContentIntent(resultPendingIntent);

        NotificationManager mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= 26) {
            String channelId = NEW_HOMEWORK_NOTIFICATIONCHANNEL_ID;
            CharSequence channelName = NEW_HOMEWORK_NOTIFICATIONCHANNEL_ID;
            int importance = NotificationManager.IMPORTANCE_LOW;
            NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName,
                    importance);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.RED);
            notificationChannel.enableVibration(true);
            notificationChannel.setImportance(NotificationManager.IMPORTANCE_DEFAULT);
            notificationChannel.setVibrationPattern(new long[] { 100, 200, 150 });
            mNotificationManager.createNotificationChannel(notificationChannel);
            mBuilder.setChannelId(NEW_HOMEWORK_NOTIFICATIONCHANNEL_ID);
        }
        mNotificationManager.notify(NEW_HOMEWORK_NOTIFICATION_ID, mBuilder.build());
    }
}

From source file:com.z3r0byte.magistify.Services.BackgroundService.java

private void unFinishedHomeworkNotification() {
    String lastCheck = configUtil.getString("last_unfinished_homework_check");
    if (lastCheck.equals(""))
        lastCheck = DateUtils.formatDate(DateUtils.addDays(new Date(), -1), "yyyyMMdd");

    Date lastCheckDate = DateUtils.parseDate(lastCheck, "yyyyMMdd");
    Date now = DateUtils.parseDate(DateUtils.formatDate(new Date(), "yyyyMMdd"), "yyyyMMdd");
    Integer hours = configUtil.getInteger("unfinished_homework_hour");
    Integer minutes = configUtil.getInteger("unfinished_homework_minute");
    if (lastCheckDate.before(now)) {
        lastCheckDate = DateUtils.addHours(lastCheckDate, 24 + hours);
        lastCheckDate = DateUtils.addMinutes(lastCheckDate, minutes);
        if (new Date().after(lastCheckDate)) {
            Appointment[] appointments = calendarDB.getUnfinishedAppointments(DateUtils.addDays(now, 1));

            if (appointments.length > 0) {

                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
                mBuilder.setSmallIcon(R.drawable.ic_unfinished_homework);
                mBuilder.setContentTitle("Huiswerk waarschuwing");

                if (appointments.length == 1) {
                    mBuilder.setContentText(appointments[0].description);
                } else {
                    String content = "Je hebt je huiswerk voor de volgende lessen van morgen nog niet afgerond:";
                    for (Appointment appointment : appointments) {
                        String string = appointment.description;
                        if (content.length() > 1) {
                            content = content + "\n" + string;
                        } else {
                            content = string;
                        }/*w  w w.j  av a2  s  .  c  om*/
                    }
                    mBuilder.setStyle(new NotificationCompat.BigTextStyle(mBuilder).bigText(content));
                    mBuilder.setContentText(content);
                }
                mBuilder.setAutoCancel(true);
                mBuilder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE);
                mBuilder.setDefaults(Notification.DEFAULT_ALL);
                mBuilder.setLights(Color.RED, 300, 200);

                Intent resultIntent = new Intent(context, HomeworkActivity.class);
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
                stackBuilder.addParentStack(NewGradeActivity.class);
                stackBuilder.addNextIntent(resultIntent);
                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
                        PendingIntent.FLAG_UPDATE_CURRENT);
                mBuilder.setContentIntent(resultPendingIntent);

                NotificationManager mNotificationManager = (NotificationManager) context
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                if (Build.VERSION.SDK_INT >= 26) {
                    String channelId = UNFINISHED_HOMEWORK_NOTIFICATIONCHANNEL_ID;
                    CharSequence channelName = UNFINISHED_HOMEWORK_NOTIFICATIONCHANNEL_ID;
                    int importance = NotificationManager.IMPORTANCE_LOW;
                    NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName,
                            importance);
                    notificationChannel.enableLights(true);
                    notificationChannel.setLightColor(Color.RED);
                    notificationChannel.enableVibration(true);
                    notificationChannel.setImportance(NotificationManager.IMPORTANCE_DEFAULT);
                    notificationChannel.setVibrationPattern(new long[] { 100, 200, 150 });
                    mNotificationManager.createNotificationChannel(notificationChannel);
                    mBuilder.setChannelId(UNFINISHED_HOMEWORK_NOTIFICATIONCHANNEL_ID);
                }
                mNotificationManager.notify(UNFINISHED_HOMEWORK_NOTIFICATION_ID, mBuilder.build());
            }

            configUtil.setString("last_unfinished_homework_check",
                    DateUtils.formatDate(new Date(), "yyyyMMdd"));
        }
    }
}

From source file:dk.bearware.gui.MainActivity.java

@Override
public void onCmdUserTextMessage(TextMessage textmessage) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    switch (textmessage.nMsgType) {
    case TextMsgType.MSGTYPE_CHANNEL:
    case TextMsgType.MSGTYPE_BROADCAST:
        accessibilityAssistant.lockEvents();
        textmsgAdapter.notifyDataSetChanged();
        accessibilityAssistant.unlockEvents();

        // audio event
        if (sounds.get(SOUND_CHANMSG) != 0)
            audioIcons.play(sounds.get(SOUND_CHANMSG), 1.0f, 1.0f, 0, 0, 1.0f);
        // TTS event
        if (ttsWrapper != null && prefs.getBoolean("broadcast_message_checkbox", false)) {
            User sender = ttservice.getUsers().get(textmessage.nFromUserID);
            String name = Utils.getDisplayName(getBaseContext(), sender);
            ttsWrapper.speak(getString(R.string.text_tts_broadcast_message, (sender != null) ? name : ""));
        }/*  ww w  .  j a  va2 s  . c o m*/
        Log.d(TAG, "Channel message in " + this.hashCode());
        break;
    case TextMsgType.MSGTYPE_USER:
        if (sounds.get(SOUND_USERMSG) != 0)
            audioIcons.play(sounds.get(SOUND_USERMSG), 1.0f, 1.0f, 0, 0, 1.0f);

        User sender = ttservice.getUsers().get(textmessage.nFromUserID);
        String name = Utils.getDisplayName(getBaseContext(), sender);
        String senderName = (sender != null) ? name : "";
        if (ttsWrapper != null && prefs.getBoolean("personal_message_checkbox", false))
            ttsWrapper.speak(getString(R.string.text_tts_personal_message, senderName));
        Intent action = new Intent(this, TextMessageActivity.class);
        Notification.Builder notification = new Notification.Builder(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel("TT_PM", "Teamtalk incoming message",
                    NotificationManager.IMPORTANCE_HIGH);
            mChannel.enableVibration(false);
            mChannel.setVibrationPattern(null);
            mChannel.enableLights(false);
            mChannel.setSound(null, null);
            notificationManager.createNotificationChannel(mChannel);
        }
        notification.setSmallIcon(R.drawable.message)
                .setContentTitle(getString(R.string.personal_message_notification, senderName))
                .setContentText(getString(R.string.personal_message_notification_hint))
                .setContentIntent(PendingIntent.getActivity(this, textmessage.nFromUserID,
                        action.putExtra(TextMessageActivity.EXTRA_USERID, textmessage.nFromUserID), 0))
                .setAutoCancel(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notification.setChannelId("TT_PM");
        }
        notificationManager.notify(MESSAGE_NOTIFICATION_TAG, textmessage.nFromUserID, notification.build());
        break;
    case TextMsgType.MSGTYPE_CUSTOM:
    default:
        break;
    }
}

From source file:org.restcomm.android.sdk.RCDevice.java

/**
 * Method returns the Notification builder
 * For Oreo devices we can have channels with HIGH and LOW importance.
 * If highImportance is true builder will be created with HIGH priority
 * For pre Oreo devices builder without channel will be returned
 * @param highImportance true if we need HIGH channel, false if we need LOW
 * @return//from ww  w . java 2 s . c  o m
 */
private NotificationCompat.Builder getNotificationBuilder(boolean highImportance) {
    NotificationCompat.Builder builder;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        if (highImportance) {
            NotificationChannel channel = new NotificationChannel(PRIMARY_CHANNEL_ID, PRIMARY_CHANNEL,
                    NotificationManager.IMPORTANCE_HIGH);
            channel.setLightColor(Color.GREEN);
            channel.enableLights(true);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            channel.enableVibration(true);
            channel.setVibrationPattern(notificationVibrationPattern);

            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                    .createNotificationChannel(channel);
            builder = new NotificationCompat.Builder(RCDevice.this, PRIMARY_CHANNEL_ID);
        } else {
            NotificationManager notificationManager = (NotificationManager) getSystemService(
                    Context.NOTIFICATION_SERVICE);
            NotificationChannel notificationChannel = new NotificationChannel(DEFAULT_FOREGROUND_CHANNEL_ID,
                    DEFAULT_FOREGROUND_CHANNEL, NotificationManager.IMPORTANCE_LOW);
            notificationManager.createNotificationChannel(notificationChannel);

            builder = new NotificationCompat.Builder(RCDevice.this, DEFAULT_FOREGROUND_CHANNEL_ID);
        }

    } else {
        builder = new NotificationCompat.Builder(RCDevice.this);
    }

    return builder;
}