Android8以上 顯示通知欄簡單實現


  private void showNotification() {
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //點擊通知本身會顯示ResultActivity
        Intent resultIntent = new Intent(this, MainActivity.class);
        resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        PendingIntent resultPendingIntent =
                PendingIntent.getActivity(
                        this,
                        0,
                        resultIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, NotificationManager.IMPORTANCE_LOW);
            mNotificationManager.createNotificationChannel(mChannel);
            notification = new Notification.Builder(this)
                    .setChannelId(CHANNEL_ID)
                    .setContentTitle("活動")
                    .setContentIntent(resultPendingIntent)
                    .setContentText("您有一項新活動")
                    .setSmallIcon(R.mipmap.ic_launcher).build();
        } else {
            mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            //構造Builder對象
            builder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("我是標題")
                    .setContentText("我是內容")
                    .setDefaults(Notification.DEFAULT_ALL)//全部
//                    .setDefaults(Notification.DEFAULT_LIGHTS)//閃光燈
//                    .setDefaults(Notification.DEFAULT_VIBRATE)//震動
//                    .setDefaults(Notification.DEFAULT_SOUND)//聲音
            ; // requires VIBRATE permission  消息提醒設置
            notification = builder.build();
            builder.setContentIntent(resultPendingIntent);
        }
        mNotificationManager.notify(1, notification);

    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM