Android Notification 通知

這是Android 通知相關的內容的總結
android中通知用到的地方很多,經常有的例如推送消息,下載時的提示等。

Android 3.0 (API level 11)之前:

使用new Notification()方式創建通知:

NotificationManager mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity( this, 0, new Intent(this, Main2Activity.class), 0); 
Notification notification = new Notification(icon, tickerText, when); 
notification.setLatestEventInfo(this, title, content, contentIntent); 
mNotifyManager .notify(NOTIFICATIONS_ID, notification);

Android 3.0 (API level 11)以後

Android 3.0開始棄用new Notification()方式,改用Notification.Builder()來創建通知:

NotificationManager mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
PendingIntent contentIntent = PendingIntent.getActivity( this, 0, new Intent(this, Main2Activity.class), 0); 
Notification notification = new Notification.Builder(this) .setSmallIcon(R.drawable.notification_icon) 
.setContentTitle("My Title") 
.setContentText("ContentText") 
.setContentIntent(contentIntent) .build();
mNotifyManager.notify(NOTIFICATIONS_ID, notification);

爲了兼容API level 11之前的版本,v4 Support Library中提供了
NotificationCompat.Builder()這個替代方法。

NotificationManager mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
PendingIntent contentIntent = PendingIntent.getActivity( this, 0, new Intent(this, Main2Activity.class), 0); 
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.notification_icon) 
.setContentTitle("My Title") 
.setContentText("ContentText") 
.setContentIntent(contentIntent); 
mNotifyManager.notify(NOTIFICATIONS_ID, mBuilder.build());

普通通知

 Intent hangIntent = new Intent(context, Main2Activity.class);
        hangIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent intent = PendingIntent.getActivity(context, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT);
         NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.mipmap.timg)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.timg))
                .setAutoCancel(true)
                .setSubText(subText + "getNormalNotification")
                .setTicker(ticker)
                .setShowWhen(true)
                .setVisibility(Notification.VISIBILITY_PUBLIC)
                .setDefaults(Notification.DEFAULT_ALL)
                .setContentIntent(intent)
                .setContentText(content)
                .setContentTitle(title);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                manager.notify(1, notification);

這裏寫圖片描述

進度條通知

    private NotificationManager getManager() {
        if (manager == null) {
            manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        }
        return manager;
    }
  Intent hangIntent = new Intent(context, Main2Activity.class);
        hangIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent intent = PendingIntent.getActivity(context, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.mipmap.timg)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.timg))
                .setAutoCancel(true)
                .setTicker(ticker)
                .setContentIntent(intent)
                .setContentText(content + "getDownloadNotification")
                .setContentTitle(title);
        new Thread(new Runnable() {
            @Override
            public void run() {
                int progress;
                for (progress = 0; progress <= 100; progress += 5) {
                    builder.setProgress(100, progress, false);
                    builder.setContentInfo(progress + "%");
                    getManager().notify(1, builder.build());
                    try {
                        Thread.sleep(1 * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                builder.setContentText("下載完成")
                        .setProgress(0, 0, false).setContentInfo("");
                getManager().notify(1, builder.build());

            }
        }).start();

這裏寫圖片描述

BigText通知

  Intent hangIntent = new Intent(context, Main2Activity.class);
        hangIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent intent = PendingIntent.getActivity(context, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.mipmap.timg)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.timg))
                .setAutoCancel(true)
                .setTicker(ticker)
                .setVisibility(Notification.VISIBILITY_PUBLIC)
                .setDefaults(Notification.DEFAULT_ALL);

        NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle();
        //bigText 給樣式設置大文本內容
        style.bigText("正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文正文");
        //setBigContentTitle 給樣式設置大文本的標題
        style.setBigContentTitle("標題");
        //SummaryText沒什麼用 可以不設置
        style.setSummaryText("末尾的文字內容");
        builder.setStyle(style).setContentIntent(intent)
                .setContentText(content)
                .setContentTitle(title);
        getManager().notify(1, notification);

這裏寫圖片描述

BigPicture通知

Intent hangIntent = new Intent(context, Main2Activity.class);
        hangIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent intent = PendingIntent.getActivity(context, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.mipmap.timg)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.timg))
                .setAutoCancel(true)
                .setTicker(ticker)
                .setVisibility(Notification.VISIBILITY_PUBLIC)
                .setDefaults(Notification.DEFAULT_ALL);

        NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
        style.setBigContentTitle("BigContentTitle");
        style.setSummaryText("SummaryText");
        style.bigPicture(BitmapFactory.decodeResource(getResources(), R.mipmap.title));
        builder.setStyle(style).setContentIntent(intent)
                .setContentText(content)
                .setContentTitle(title);
       getManager().notify(1, notification);

這裏寫圖片描述

懸掛通知

Intent hangIntent = new Intent();
        hangIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        hangIntent.setClass(context, Main2Activity.class);
        PendingIntent hangPendingIntent = PendingIntent.getActivity(context, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        NotificationCompat.Builder builder =  new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.mipmap.timg)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.timg))
                .setAutoCancel(true)
                .setVisibility(VISIBILITY_PUBLIC)
                .setFullScreenIntent(hangPendingIntent, true)
                .setContentText(content)
                .setContentTitle(title);
        getManager().notify(1, notification);     

這裏寫圖片描述

5.0鎖屏通知

Android 5.0(API level 21)開始,通知可以顯示在鎖屏上。用戶可以通過設置選擇是否允許敏感的通知內容顯示在安全的鎖屏上。
你的應用可以通過setVisibility()控制通知的顯示等級:

VISIBILITY_PRIVATE : 顯示基本信息,如通知的圖標,但隱藏通知的全部內容
VISIBILITY_PUBLIC : 顯示通知的全部內容
VISIBILITY_SECRET : 不顯示任何內容,包括圖標

這裏寫圖片描述

Android8.0 適配通知欄

查看官方文檔 https://developer.android.com/preview/features/notification-channels.html

文檔裏是這樣寫的:

If you targetAndroid O and post a notification without specifying a valid notificationschannel, the notification fails to post and the system logs an error.

大意就是說,如果在Android O發送通知需要設置notificationchannel,否則通知會發送失敗。

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    NotificationChannel channel = new NotificationChannel("通知渠道ID",
                    "通知渠道名稱", NotificationManager.IMPORTANCE_DEFAULT);
    channel.enableLights(true); //設置開啓指示燈,如果設備有的話
    channel.setLightColor(Color.RED); //設置指示燈顏色
    channel.setShowBadge(true); //設置是否顯示角標
    channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);//設置是否應在鎖定屏幕上顯示此頻道的通知
    channel.setDescription("通知渠道描述");//設置渠道描述
    channel.setVibrationPattern(new long[]{100,200,300,400,500,600});//設置震動頻率
    channel.setBypassDnd(true);//設置是否繞過免打擾模式
    mNotificationManager.createNotificationChannel(channel);
  Intent hangIntent = new Intent(context, Main2Activity.class);
        hangIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent intent = PendingIntent.getActivity(context, 0, hangIntent, PendingIntent.FLAG_CANCEL_CURRENT);
         NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext())
                .setSmallIcon(R.mipmap.timg)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.timg))
                .setAutoCancel(true)
                .setSubText(subText + "getNormalNotification")
                .setTicker(ticker)
                .setShowWhen(true)
                .setVisibility(Notification.VISIBILITY_PUBLIC)
                .setDefaults(Notification.DEFAULT_ALL)
                .setContentIntent(intent)
                .setContentText(content)
                .setContentTitle(title);
          getManager().notify(1, notification);

鎖屏通知,懸掛通知等測試時記得要在手機裏開啓相關權限,很多手機權限默認關閉
這裏寫圖片描述

參考資料:
Android Notification 通知樣式總結
https://shoewann0402.github.io/2016/05/12/Android-Notification-%E9%80%9A%E7%9F%A5%E6%A0%B7%E5%BC%8F%E6%80%BB%E7%BB%93/
Android通知欄介紹與適配總結
https://blog.csdn.net/jiankeufo/article/details/77977564

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章