com.sxt.chat.utils.NotificationHelper.java Source code

Java tutorial

Introduction

Here is the source code for com.sxt.chat.utils.NotificationHelper.java

Source

/*
 * Copyright 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.sxt.chat.utils;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;

import com.sxt.chat.R;

/**
 * created by sxt at 2018/11/20
 * <p>
 * Android 8.1API27??? ,??
 */
public class NotificationHelper extends ContextWrapper {
    private Context context;
    private Uri soundUri;
    private NotificationManager manager;
    public static final String DEFAULT_CHANNEL = "DEFAULT";
    public static final String CUSTOM_NOTIFY_CHANNEL = "CUSTOM_NOTIFY_CHANNEL";
    private final String GROUP_KEY_WORK = "GROUP_KEY_WORK";

    /**
     * ? notification manager.
     */
    public NotificationManager getManager() {
        if (manager == null) {
            manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        }
        return manager;
    }

    /**
     * ?
     * <p>
     * note : notify() ? ???,?? so, Create?
     */
    public NotificationHelper(Context ctx) {
        super(ctx);
        context = ctx;
        soundUri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notify_message);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            AudioAttributes att = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build();
            NotificationChannel channel = new NotificationChannel(DEFAULT_CHANNEL, "Channel",
                    NotificationManager.IMPORTANCE_HIGH);
            channel.setSound(soundUri, att);
            channel.setLightColor(Color.YELLOW);
            channel.setShowBadge(true);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            getManager().createNotificationChannel(channel);

            NotificationChannel chanCustom = new NotificationChannel(CUSTOM_NOTIFY_CHANNEL, "Custom Layout Channel",
                    NotificationManager.IMPORTANCE_HIGH);
            channel.setSound(soundUri, att);
            chanCustom.setLightColor(Color.RED);
            chanCustom.setShowBadge(true);
            chanCustom.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            getManager().createNotificationChannel(chanCustom);
        }
    }

    /**
     * ?? NotificationCompat.Builder
     */
    private NotificationCompat.Builder getNotificationBuilderByChannel(String... channel) {
        NotificationCompat.Builder builder;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            builder = new NotificationCompat.Builder(getApplicationContext(),
                    channel == null || channel.length == 0 ? DEFAULT_CHANNEL : channel[0]);
        } else {
            builder = new NotificationCompat.Builder(this).setSound(soundUri);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//8.0 && 7.0? 
                builder.setPriority(NotificationManager.IMPORTANCE_HIGH);
            } else {
                builder.setPriority(NotificationCompat.PRIORITY_HIGH);
            }
        }
        return builder;
    }

    /**
     * 1
     * <p>
     * note: ?(?)
     * ?NotificationCompat.BigTextStyle()
     */
    private NotificationCompat.Builder buildNotificationText(String title, String body,
            PendingIntent pendingIntent) {
        return getNotificationBuilderByChannel().setAutoCancel(true).setSmallIcon(getSmallIcon())
                .setLargeIcon(getLargeIcon()).setContentTitle(title).setContentText(body)
                .setBadgeIconType(NotificationCompat.BADGE_ICON_LARGE).setContentIntent(pendingIntent)
                //.setTimeoutAfter(3000)//??
                //.setNumber(1127)//999 999
                .setBadgeIconType(NotificationCompat.BADGE_ICON_LARGE)//,, 
                .setStyle(new NotificationCompat.BigTextStyle().setBigContentTitle(title).bigText(body));
    }

    /**
     * 2 Action
     * <p>
     *
     * @param actions ? 3
     */
    private NotificationCompat.Builder buildNotificationTextAction(String title, String body,
            PendingIntent pendingIntent, NotificationCompat.Action... actions) {
        NotificationCompat.Builder builder = getNotificationBuilderByChannel().setAutoCancel(true)
                .setSmallIcon(getSmallIcon()).setLargeIcon(getLargeIcon()).setContentTitle(title)
                .setContentText(body).setContentIntent(pendingIntent)
                .setStyle(new NotificationCompat.BigTextStyle().setBigContentTitle(title).bigText(body));

        if (null != actions && actions.length > 0) {
            for (NotificationCompat.Action action : actions) {
                builder.addAction(action);
            }
        }
        return builder;
    }

    /**
     * 
     * <p>
     * ???, ?
     */
    private NotificationCompat.Builder buildNotificationImage(String title, String body, Bitmap imgBitmap,
            PendingIntent pendingIntent) {
        return getNotificationBuilderByChannel().setAutoCancel(true).setSmallIcon(getSmallIcon())
                .setLargeIcon(getLargeIcon()).setContentTitle(title).setContentText(body)
                .setContentIntent(pendingIntent).setStyle(new NotificationCompat.BigPictureStyle()
                        .setBigContentTitle(title).bigLargeIcon(imgBitmap).bigPicture(imgBitmap));
    }

    /**
     * 2 Action
     * <p>
     * ???, ?
     */
    private NotificationCompat.Builder buildNotificationImageAction(String title, String body, Bitmap imgBitmap,
            PendingIntent pendingIntent, NotificationCompat.Action... actions) {
        NotificationCompat.Builder builder = getNotificationBuilderByChannel().setAutoCancel(true)
                .setSmallIcon(getSmallIcon()).setLargeIcon(getLargeIcon()).setContentTitle(title)
                .setContentText(body).setContentIntent(pendingIntent)
                .setStyle(new NotificationCompat.BigPictureStyle().setBigContentTitle(title).bigLargeIcon(imgBitmap)
                        .bigPicture(imgBitmap));

        if (null != actions && actions.length > 0) {
            for (NotificationCompat.Action action : actions) {
                builder.addAction(action);
            }
        }
        return builder;
    }

    public NotificationCompat.Builder buildNotificationText(String title, String body, PendingIntent pendingIntent,
            NotificationCompat.Action... actions) {
        return null != actions && actions.length > 0
                ? buildNotificationTextAction(title, body, pendingIntent, actions)
                : buildNotificationText(title, body, pendingIntent);
    }

    public NotificationCompat.Builder buildNotificationImage(String title, String body, Bitmap imgBitmap,
            PendingIntent pendingIntent, NotificationCompat.Action... actions) {
        return null != actions && actions.length > 0
                ? buildNotificationImageAction(title, body, imgBitmap, pendingIntent, actions)
                : buildNotificationImage(title, body, imgBitmap, pendingIntent);
    }

    /**
     * View
     */
    public NotificationCompat.Builder buildCustomNotificationDefault(String title, String body,
            PendingIntent pendingIntent) {
        NotificationCompat.Builder builder = getNotificationBuilderByChannel();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // ?
            RemoteViews notificationLayout = new RemoteViews(getPackageName(), R.layout.notification_small);
            RemoteViews notificationLayoutExpanded = new RemoteViews(getPackageName(), R.layout.notification_large);
            builder.setStyle(new NotificationCompat.DecoratedCustomViewStyle())
                    .setCustomContentView(notificationLayout).setCustomBigContentView(notificationLayoutExpanded);
        } else {
            builder.setSound(soundUri)
                    .setStyle(new NotificationCompat.BigTextStyle().setBigContentTitle(title).bigText(body));
        }
        return builder.setAutoCancel(true).setSmallIcon(getSmallIcon()).setLargeIcon(getLargeIcon())
                .setContentTitle(title).setContentText(body).setContentIntent(pendingIntent);
    }

    /**
     * ??
     */
    public void notify(int id, NotificationCompat.Builder notification) {
        getManager().notify(id, notification.build());
    }

    /**
     * ?
     */
    private Bitmap getLargeIcon() {
        return BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_ar_photo_main_blue_24dp);
    }

    /**
     * ??
     */
    private int getSmallIcon() {
        return R.drawable.ic_vector_notifications_24dp;
    }

}