Android常用通知

1.一般的通知步骤

    1. Notification代码如下
//自定义打开的界面
        Intent intent = new Intent(this, NoticeReceiveActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //intent里面可以携带参数
        intent.putExtra("key","来自通知");
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 9
                , intent, PendingIntent.FLAG_UPDATE_CURRENT);

//1,获取NotificationManager实例
         nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //2,创建Notification实例
        Notification.Builder builder = new Notification.Builder(this);
         builder.setAutoCancel(true)  //设置点击通知后自动取消通知
                .setContentTitle("标题")  //通知标题
                .setContentText("内容简介")  //通知第二行的内容
                .setContentIntent(pendingIntent)  //点击通知后,发送指定的PendingIntent
                .setSmallIcon(R.mipmap.scbg);  //通知图标,必须设置否则通知不显示


        Notification build = builder.build();
        //3,发送通知
        nm.notify(1,build);
    1. NotificationCompat代码如下
 NotificationManager nm;
    public void testOne2(View view) {
        //自定义打开的界面
        Intent intent = new Intent(this, NoticeReceiveActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //intent里面可以携带参数
        intent.putExtra("key","来自通知");
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 9
                , intent, PendingIntent.FLAG_UPDATE_CURRENT);

        //1,获取NotificationManager实例
         nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        //2,获取通知的构造器
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        Notification notification = builder
                .setContentTitle("任意标题")//设置标题
                .setContentText("设置任意内容白费劲啊飞机的飞机啊房间爱疯没法讲方法诶白费劲啊飞机的飞机啊房间爱疯没法讲方法诶白费劲啊飞机的飞机啊房间爱疯没法讲方法诶白费劲啊飞机的飞机啊房间爱疯没法讲方法诶")
                .setAutoCancel(true)//设置可取消
                .setContentInfo("设置任意附件信息")
                .setShowWhen(true)//设置是否显示时间
                .setTicker("通知来了")//设置通知首次出现提示
                .setPriority(Notification.PRIORITY_DEFAULT)//设置通知的优先级,默认为0
                .setDefaults(Notification.DEFAULT_VIBRATE)//设置振动声音等,需要振动权限
                .setContentIntent(pendingIntent)//自定义打开的界面
                .setWhen(System.currentTimeMillis())//设置时间,long类型自动转换
                .setSmallIcon(R.mipmap.scbg)//设置小图标,必须设置
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.cktl4))//设置大图标
                .build();
        //3,发送通知
        nm.notify(2,notification);
    }

2.几种常用通知工具使用

  • 1.对于8.0适配处理,需要创建通知渠道
  //提前对通知渠道处理,默认创建多种
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannels.createAllNotificationChannels(this);
        }
    1. 普通通知
public void normal(View view) {
        NotifyUtils notifyUtils = new NotifyUtils(this, NotificationChannels.LOW);

        notifyUtils.notifyNormal(null,R.mipmap.logo,0,null,"title",
                "content",2,false,false,false);
    }
    1. 自定义布局通知
      1.这种方法有的手机会有高度限制(自定义布局高度压缩为常见通知高度,适用高度和普通通知高度相同)
 public void custom1(View view) {
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notice);

        NotifyUtils notifyUtils = new NotifyUtils(this, NotificationChannels.LOW);

        notifyUtils.notifyCustomView(remoteViews,null,
                R.mipmap.logo,0,"hello",9,false,false,false);
    }

2.正常布局

public void custom2(View view) {
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.notice);

        NotifyUtils notifyUtils = new NotifyUtils(this, NotificationChannels.LOW);

        notifyUtils.notifyCustomView2(remoteViews,null,
                R.mipmap.logo,0,"hello",9,false,false,false);
    }
  • 3.带大图通知
public void bigIconListener(View view) {//大图在魅族上会重叠
        NotifyUtils notifyUtils = new NotifyUtils(this, NotificationChannels.LOW);
        notifyUtils.notifyBigPic(null,R.mipmap.cktl4,0,
                "hello","邮件","这是一封重要的邮件",
                R.mipmap.scbg,8,false,true,true);
    }
  • 4.多行文字通知
 public void moreTextListener(View view) {
        NotifyUtils notifyUtils = new NotifyUtils(this, NotificationChannels.IMPORTANCE);

        notifyUtils.notifyNormailMoreline(null,R.mipmap.logo,0,
                null,"多行文字",
                "这是一封重要的邮件这是一封重要的邮件这是一封重要的邮件这是一封重要的邮件这是一封重要的邮件" +
                        "这是一封重要的邮件这是一封重要的邮件这是一封重要的邮件",
                7,false,false,false);

    }
  • 5.带点击通知
public void buttonListener(View view) {
        NotifyUtils notifyUtils = new NotifyUtils(this, NotificationChannels.IMPORTANCE);
        notifyUtils.notifyButton(R.mipmap.cktl4,0,R.mipmap.cktl4,"左侧文字",null,
                R.mipmap.logo,"右侧",null,null,"带按钮的通知",
                "通知通知套中套总投资天天",23,false,false,false);
    }
  • 6,head up
    经测试,样式和带按钮点击类似
public void headupListener(View view) {

        NotifyUtils notifyUtils = new NotifyUtils(this, NotificationChannels.IMPORTANCE);
        notifyUtils.notifyHeadUp(null,R.mipmap.logo,R.mipmap.scbg,
                "通知","标题","简单内容",R.mipmap.ic_launcher,
                "左边",null,R.mipmap.scbg,"右边"
                ,null,22, false,false,false);

    }

3,创建通知渠道类

public class NotificationChannels {
    public final static String CRITICAL = "critical";
    public final static String IMPORTANCE = "importance";
    public final static String DEFAULT = "default";
    public final static String LOW = "low";
    public final static String MEDIA = "media";

    public static final String CHANNEL_CRITICAL = "Critical events";
    public static final String CHANNEL_IMPORTANCE = "Importance events";
    public static final String CHANNEL_DEFAULT = "Default events";
    public static final String CHANNEL_LOW = "Low events";
    public static final String CHANNEL_MEDIA = "Media events";

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static void createAllNotificationChannels(Context context) {
        Log.e("MMM", "createAllNotificationChannels: " );
        NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        if(nm == null) {
            return;
        }

        //创建全部渠道,也可以根据需求创建
        NotificationChannel mediaChannel = new NotificationChannel(
                MEDIA,
                CHANNEL_MEDIA,
                NotificationManager.IMPORTANCE_DEFAULT);
        mediaChannel.setSound(null,null);
        mediaChannel.setVibrationPattern(null);

        nm.createNotificationChannels(Arrays.asList(
                new NotificationChannel(
                        CRITICAL,
                        CHANNEL_CRITICAL,
                        NotificationManager.IMPORTANCE_HIGH),
                new NotificationChannel(
                        IMPORTANCE,
                       CHANNEL_IMPORTANCE,
                        NotificationManager.IMPORTANCE_DEFAULT),
                new NotificationChannel(
                        DEFAULT,
                        CHANNEL_DEFAULT,
                        NotificationManager.IMPORTANCE_LOW),
                new NotificationChannel(
                        LOW,
                        CHANNEL_LOW,
                        NotificationManager.IMPORTANCE_MIN),
                //custom notification channel
                mediaChannel
        ));
    }
}

4.通知类

public class NotifyUtils {

    private Context mContext;
    private NotificationManager mNm;
    private NotificationCompat.Builder mBuilder;
    private Notification notification;

    public NotifyUtils(Context context,String channelId) {
        mContext = context;
        // 获取系统服务来初始化对象
        mNm = (NotificationManager) mContext
                .getSystemService(Activity.NOTIFICATION_SERVICE);
        //判断是否是8.0,8.0创建通知渠道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//默认聊天高级通知
            mBuilder = new NotificationCompat.Builder(mContext,channelId);
        }else {
            mBuilder = new NotificationCompat.Builder(mContext);
        }

    }


    /**
     * 设置在顶部通知栏中的各种信息
     *
     * @param pendingIntent
     * @param smallIcon
     * @param ticker
     */
    private void setCompatBuilder(PendingIntent pendingIntent, int smallIcon, int largeIcon,
                                  String ticker,
                                  String title, String content, boolean sound, boolean vibrate, boolean lights) {


        mBuilder.setContentIntent(pendingIntent);// 该通知要启动的Intent
        mBuilder.setSmallIcon(smallIcon);// 设置顶部状态栏的小图标
        mBuilder.setTicker(ticker);// 在顶部状态栏中的提示信息

        mBuilder.setContentTitle(title);// 设置通知中心的标题
        mBuilder.setContentText(content);// 设置通知中心中的内容
        mBuilder.setWhen(System.currentTimeMillis());
        if (largeIcon != 0){//默认0是没有大图
            mBuilder.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), largeIcon));
        }
        /*
         * 将AutoCancel设为true后,当你点击通知栏的notification后,它会自动被取消消失,
         * 不设置的话点击消息后也不清除,但可以滑动删除
         */
        mBuilder.setAutoCancel(true);
        // 将Ongoing设为true 那么notification将不能滑动删除
        // notifyBuilder.setOngoing(true);
        /*
         * 从Android4.1开始,可以通过以下方法,设置notification的优先级,
         * 优先级越高的,通知排的越靠前,优先级低的,不会在手机最顶部的状态栏显示图标
         */
        mBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
        /*
         * Notification.DEFAULT_ALL:铃声、闪光、震动均系统默认。
         * Notification.DEFAULT_SOUND:系统默认铃声。
         * Notification.DEFAULT_VIBRATE:系统默认震动。
         * Notification.DEFAULT_LIGHTS:系统默认闪光。
         * notifyBuilder.setDefaults(Notification.DEFAULT_ALL);
         */
        int defaults = 0;

        if (sound) {
            defaults |= Notification.DEFAULT_SOUND;
        }
        if (vibrate) {
            defaults |= Notification.DEFAULT_VIBRATE;
        }
        if (lights) {
            defaults |= Notification.DEFAULT_LIGHTS;
        }

        mBuilder.setDefaults(defaults);
    }

    /**普通的通知
     * @param pendingIntent
     * @param smallIcon
     * @param ticker
     * @param title
     * @param content
     * @param id
     * @param sound
     * @param vibrate
     * @param lights
     */
    public void notifyNormal(PendingIntent pendingIntent, int smallIcon,int largeIcon,
                                       String ticker, String title, String content, int id,
                                       boolean sound, boolean vibrate, boolean lights) {
        setCompatBuilder(pendingIntent, smallIcon, largeIcon, ticker, title, content, sound, vibrate, lights);
        sent(id);
    }

    /**
     * 自定义视图的通知(默认64dp)
     *
     * @param remoteViews
     * @param pendingIntent
     * @param smallIcon
     * @param ticker
     */
    public void notifyCustomView(RemoteViews remoteViews, PendingIntent pendingIntent,
                                  int smallIcon, int largeIcon, String ticker, int id,
                                  boolean sound, boolean vibrate, boolean lights) {

        setCompatBuilder(pendingIntent, smallIcon, largeIcon, ticker, null, null, sound, vibrate, lights);

        notification = mBuilder.build();
        notification.contentView = remoteViews;
        // 发送该通知
        mNm.notify(id, notification);
    }

    /**自定义视图的通知
     * @param remoteViews
     * @param pendingIntent
     * @param smallIcon
     * @param ticker
     * @param id
     * @param sound
     * @param vibrate
     * @param lights
     */
    public void notifyCustomView2(RemoteViews remoteViews, PendingIntent pendingIntent,
                                 int smallIcon, int largeIcon, String ticker, int id,
                                 boolean sound, boolean vibrate, boolean lights){

        setCompatBuilder(pendingIntent, smallIcon, largeIcon, ticker, null, null, sound, vibrate, lights);

        Notification notification = mBuilder.build();
        notification.bigContentView=remoteViews;
        mNm.notify(id, notification);
    }

    /**
     * 容纳大图片的通知
     *
     * @param pendingIntent
     * @param smallIcon
     * @param ticker
     * @param title
     * @param bigPic
     */
    public void notifyBigPic(PendingIntent pendingIntent, int smallIcon, int largeIcon, String ticker,
                              String title, String content, int bigPic, int id,boolean sound, boolean vibrate, boolean lights) {

        setCompatBuilder(pendingIntent, smallIcon, largeIcon, ticker, title, null, sound, vibrate, lights);
        NotificationCompat.BigPictureStyle picStyle = new NotificationCompat.BigPictureStyle();
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inScaled = true;
        options.inSampleSize = 2;
        Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(),
                bigPic, options);
        picStyle.bigPicture(bitmap);
        picStyle.bigLargeIcon(bitmap);
        mBuilder.setContentText(content);
        mBuilder.setStyle(picStyle);
        sent(id);
    }

    /**
     * 可以容纳多行提示文本的通知信息 (因为在高版本的系统中才支持,所以要进行判断)
     *
     * @param pendingIntent
     * @param smallIcon
     * @param ticker
     * @param title
     * @param content
     */
    public void notifyNormailMoreline(PendingIntent pendingIntent, int smallIcon, int largeIcon,
                                      String ticker,
                                        String title, String content, int id, boolean sound, boolean vibrate, boolean lights) {

        final int sdk = Build.VERSION.SDK_INT;
        if (sdk < Build.VERSION_CODES.JELLY_BEAN) {
            notifyNormal(pendingIntent, smallIcon, largeIcon,ticker, title, content, id, sound, vibrate, lights);
        } else {
            setCompatBuilder(pendingIntent, smallIcon, largeIcon,ticker, title,content,true, true, false);

            NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle()
                    .bigText(content);
            mBuilder.setStyle(bigTextStyle);
            sent(id);
        }
    }

    /**
     * 里面有两个按钮的通知
     *
     * @param smallIcon
     * @param leftbtnicon
     * @param lefttext
     * @param leftPendIntent
     * @param rightbtnicon
     * @param righttext
     * @param rightPendIntent
     * @param ticker
     * @param title
     * @param content
     */
    public void notifyButton(int smallIcon, int largeIcon, int leftbtnicon, String lefttext, PendingIntent leftPendIntent,
                             int rightbtnicon, String righttext, PendingIntent rightPendIntent, String ticker,
                              String title, String content, int id, boolean sound, boolean vibrate, boolean lights) {


        setCompatBuilder(rightPendIntent, smallIcon, largeIcon, ticker, title, content, sound, vibrate, lights);
        mBuilder.addAction(leftbtnicon,
                lefttext, leftPendIntent);
        mBuilder.addAction(rightbtnicon,
                righttext, rightPendIntent);
        sent(id);
    }

    public void notifyHeadUp(PendingIntent pendingIntent, int smallIcon, int largeIcon,
                              String ticker, String title, String content, int leftbtnicon, String lefttext,
                              PendingIntent leftPendingIntent, int rightbtnicon, String righttext,
                              PendingIntent rightPendingIntent, int id,
                              boolean sound, boolean vibrate, boolean lights) {

        setCompatBuilder(pendingIntent, smallIcon, largeIcon,ticker, title, content, sound, vibrate, lights);
        //mBuilder.setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), largeIcon));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mBuilder.addAction(leftbtnicon,
                    lefttext, leftPendingIntent);
            mBuilder.addAction(rightbtnicon,
                    righttext, rightPendingIntent);
        } else {
            Toast.makeText(mContext, "版本低于Andriod5.0,无法体验HeadUp样式通知", Toast.LENGTH_SHORT).show();
        }
        sent(id);
    }

    /**
     * 发送通知
     */
    private void sent(int id) {
        notification = mBuilder.build();
        // 发送该通知
        mNm.notify(id, notification);
    }

    public void clear() {
        // 取消通知
        mNm.cancelAll();
    }
    public void removeId(int id){
        //id不存在会崩溃
        mNm.cancel(id);
    }
}

5.参考文献

上面都是常用简单通知,其他类型的通知,及适配问题可以参考其他文献.
Android–通知之Notification
Android通知栏介绍与适配总结
是时候来了解android7了:通知直接回复
Android7.0 通知直接回复
Android通知栏微技巧,8.0系统中通知栏的适配
Android 8.0中各种通知写法汇总

6,源码

demo

你可能感兴趣的:(通知)