qingmei2
4/10/2018 - 6:52 AM

NotificationUtils

NotificationUtils

## 使用方式

首先在Activity或者Application中进行注册:

```
 NotificationHelper.register(application);
```

然后尽情的使用:

```java
NotificationModel model1 = new NotificationModel.Builder()
                .setId(1)
                .setSmallIconRes(R.mipmap.ic_launcher_round)
                .setTitle("发送一条通知哇")
                .setContent("通知内容")
                .setPriority(2)
                .setSoundRes(R.raw.alert)
                .setFloatMode(true)
                .setOnIntentInit(intent -> intent.putExtra("name", "jack"))
                .build();
NotificationHelper.getInstance().sendNotification(model1)
```
public final class NotificationModel {

    /**
     * 通知的id,请保证通知id的唯一性(以用于实现更新、删除指定通知等功能)
     *
     * @see NotificationManager#notify(int, Notification)
     */
    public int id;

    /**
     * 兼容Android O以上版本的更新,默认为字符串"channelId"
     */
    public String channelId = "channelId";

    /**
     * 通知的小图标资源id
     */
    @DrawableRes
    public int smallIconRes;

    /**
     * 通知的title
     *
     * @see NotificationCompat.Builder#setContentTitle(CharSequence)
     */
    public String title;

    /**
     * 通知的内容
     *
     * @see NotificationCompat.Builder#setContentText(CharSequence)
     */
    public String content;

    /**
     * 用户点击通知,是否自动cancel掉,默认为true
     *
     * @see NotificationCompat.Builder#setAutoCancel(boolean)
     */
    public boolean autoCancel = true;

    /**
     * 要跳转的&&返回栈的Activity
     * <p>
     * 你需要在Manifest文件中对Activity的返回栈做出如下配置:
     * <pre>
     *     <code>
     * < activity
     *      android:name=".SecondActivity"
     *      android:parentActivityName=".ThirdActivity">
     *          < meta-data
     *              android:name="android.support.PARENT_ACTIVITY"
     *              android:value=".ThirdActivity" />
     * < /activity>
     *     </code>
     * </pre>
     *
     * @see android.content.Intent
     * @see android.support.v4.app.TaskStackBuilder#addParentStack(Class)
     */
    public Class<? extends Activity> backStackActivity;

    /**
     * 您可以根据需要设置通知的优先级。优先级充当一个提示,提醒设备 UI 应该如何显示通知。
     * </p>
     * 有五个优先级别,范围从 PRIORITY_MIN (-2) 到 PRIORITY_MAX (2);如果未设置,则优先级默认为 PRIORITY_DEFAULT (0)。
     *
     * @see NotificationCompat#PRIORITY_MIN
     * @see NotificationCompat#PRIORITY_LOW
     * @see NotificationCompat#PRIORITY_DEFAULT
     * @see NotificationCompat#PRIORITY_HIGH
     * @see NotificationCompat#PRIORITY_MAX
     */
    public int priority = NotificationCompat.PRIORITY_DEFAULT;

    /**
     * 设置通知背景音乐
     */
    @RawRes
    public int soundRes;

    /**
     * 是否属于浮动通知
     * <p>
     * 可能触发浮动通知的条件示例包括:
     * <p>
     * 用户的 Activity 处于全屏模式中(应用使用 fullScreenIntent),或者
     * <p>
     * 通知具有较高的优先级并使用铃声或振动
     */
    public boolean floatMode = false;

    /**
     * 负责传值给其他界面
     */
    public OnIntentInit onIntentInit;

    private NotificationModel() {

    }

    private NotificationModel(Builder target) {
        this.id = target.id;
        this.channelId = target.channelId;
        this.smallIconRes = target.smallIconRes;
        this.title = target.title;
        this.content = target.content;
        this.autoCancel = target.autoCancel;
        this.backStackActivity = target.backStackActivity;
        this.priority = target.priority;
        this.soundRes = target.soundRes;
        this.floatMode = target.floatMode;
        this.onIntentInit = target.onIntentInit;
    }

    public static class Builder {

        private int id;

        private String channelId = "channelId";

        @DrawableRes
        private int smallIconRes;

        private String title;

        private String content;

        private boolean autoCancel = true;

        private Class<? extends Activity> backStackActivity;

        private int priority = NotificationCompat.PRIORITY_DEFAULT;

        @RawRes
        private int soundRes;

        private boolean floatMode = false;

        private OnIntentInit onIntentInit;

        public Builder() {

        }

        public Builder setId(int id) {
            this.id = id;
            return this;
        }

        public Builder setChannelId(String channelId) {
            this.channelId = channelId;
            return this;
        }

        public Builder setSmallIconRes(int smallIconRes) {
            this.smallIconRes = smallIconRes;
            return this;
        }

        public Builder setTitle(String title) {
            this.title = title;
            return this;
        }

        public Builder setContent(String content) {
            this.content = content;
            return this;
        }

        public Builder setAutoCancel(boolean autoCancel) {
            this.autoCancel = autoCancel;
            return this;
        }

        public Builder setBackStackActivity(Class<? extends Activity> backStackActivity) {
            this.backStackActivity = backStackActivity;
            return this;
        }

        public Builder setPriority(int priority) {
            this.priority = priority;
            return this;
        }

        public Builder setSoundRes(int soundRes) {
            this.soundRes = soundRes;
            return this;
        }

        public Builder setOnIntentInit(OnIntentInit onIntentInit) {
            this.onIntentInit = onIntentInit;
            return this;
        }

        /**
         * 必须设置:
         * <p>
         * 用户的 Activity 处于全屏模式中(应用使用 fullScreenIntent),或者
         * <p>
         * 通知具有较高的优先级并使用铃声或振动
         */
        public Builder setFloatMode(boolean floatMode) {
            this.floatMode = floatMode;
            return this;
        }

        public NotificationModel build() {
            return new NotificationModel(this);
        }
    }

    public interface OnIntentInit {

        Intent onIntentInit(Intent intent);
    }
}
public final class NotificationHelper {

    private volatile static NotificationHelper instance;

    private Application application;
    private NotificationManager mNotificationManager;

    private NotificationHelper(Application application) {
        this.application = application;
        this.mNotificationManager = (NotificationManager) application.getSystemService(Context.NOTIFICATION_SERVICE);
    }

    public static NotificationHelper register(Application application) {
        return getInstance(application);
    }

    public static NotificationHelper getInstance() {
        return getInstance(null);
    }

    private static NotificationHelper getInstance(Application application) {
        if (instance == null) {
            synchronized (NotificationHelper.class) {
                if (application == null)
                    throw new NullPointerException("You need call NotificationHelper.register() first.");
                if (instance == null) {
                    instance = new NotificationHelper(application);
                }
            }
        }
        return instance;
    }

    public void sendNotification(NotificationModel notification) {
        Intent resultIntent = new Intent(application, SecondActivity.class);
        if (notification.onIntentInit != null)
            resultIntent = notification.onIntentInit.onIntentInit(resultIntent);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(application);
        stackBuilder.addParentStack(SecondActivity.class);
        stackBuilder.addNextIntent(resultIntent);

        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
                0,
                PendingIntent.FLAG_UPDATE_CURRENT
        );

        NotificationCompat.Builder builder;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel();
            builder = getNotificationBuilder_26(notification.channelId);
        } else {
            builder = getNotificationBuilder_25();
        }

        builder.setSmallIcon(notification.smallIconRes)
                .setPriority(notification.priority)
                .setContentTitle(notification.title)
                .setContentText(notification.content)
                .setAutoCancel(notification.autoCancel)
                .setContentIntent(resultPendingIntent);

        if (notification.soundRes != 0) {
            Uri uri = Uri.parse("android.resource://com.qingmei2.notificationdemo/" + notification.soundRes);
            builder.setSound(uri);
        }

        mNotificationManager.notify(notification.id, builder.build());
    }

    private NotificationCompat.Builder getNotificationBuilder_25() {
        return new NotificationCompat.Builder(application);
    }

    @TargetApi(value = Build.VERSION_CODES.O)
    private NotificationCompat.Builder getNotificationBuilder_26(String channelId) {
        return new NotificationCompat.Builder(application, channelId);
    }

    @TargetApi(value = Build.VERSION_CODES.O)
    private void createNotificationChannel() {
        NotificationChannel channel = new NotificationChannel("channelId",
                "Channel", NotificationManager.IMPORTANCE_DEFAULT);
        channel.enableLights(true);
        channel.setLightColor(Color.RED);
        channel.setShowBadge(true);
        mNotificationManager.createNotificationChannel(channel);
    }

    public void updateNotification(NotificationModel notification) {
        this.sendNotification(notification);
    }

    public void deleteNotification(NotificationModel notification) {
        this.deleteNotification(notification.id);
    }

    public void deleteNotification(int notificationId) {
        mNotificationManager.cancel(notificationId);
    }

    public void deleteAllNotifications() {
        mNotificationManager.cancelAll();
    }

}
public interface INotificationFactory {

    NotificationModel provide();
}