Android開發學習——使用通知

在按照書中的例子使用通知在設備上沒有通知,查找資料後發現Android8後通知須要NotificationChannel,兼容 Android 8.0的通知以下:ide

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

                Intent intent = new Intent(this,NotificationMain2Activity.class);
                PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);

                // 構建 Notification
                Notification.Builder builder = new Notification.Builder(this);
                builder.setContentTitle("ContentTitle")
                        .setSmallIcon(R.drawable.ic_launcher_background)
                        .setContentText("Content Text Here")
                        .setContentIntent(pi)
                        .setAutoCancel(true);

                // 兼容 Android 8.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                    String channelId = "ET_Notification_001";
                    String channelName = "ETtNotificationName";
                    // 第三個參數表示通知的重要程度
                    NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
                    // 冊後除非卸載再安裝不然不改變
                    notificationManager.createNotificationChannel(notificationChannel);
                    builder.setChannelId(channelId);
                }
                // 發出通知
                notificationManager.notify(1, builder.build());
相關文章
相關標籤/搜索