Android8.0 以上自定义通知声音

480 阅读1分钟

Android8.0 以上自定义NotificationChannel声音

public void createNotification(String title, String message) {
    Uri soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.msg);
    
    //ARouter获取class 配置跳转
    Postcard postcard = ARouter.getInstance().build("/im/MessageActivity");
    LogisticsCenter.completion(postcard);
    Class<?> destination = postcard.getDestination();
    Intent intent = new Intent(this, destination);
    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    Notification.Builder mBuilder = new Notification.Builder(MainActivity.this);
    mBuilder.setSound(soundUri);
    mBuilder.setSmallIcon(R.mipmap.ic_launcher);
    mBuilder.setContentTitle(title)
            .setContentText(message)
            .setAutoCancel(false)
            .setContentIntent(pendingIntent)
            .setColor(Color.GREEN);

    NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel notificationChannel = new NotificationChannel("111111", "NOTIFICATION_CHANNEL_NAME", importance);
        notificationChannel.enableLights(true);//闪光灯
        notificationChannel.setLightColor(Color.RED);//制定闪灯是灯光颜色
        notificationChannel.enableVibration(true);//是否允许震动
        notificationChannel.setVibrationPattern(new long[]{100, 100, 200});//设置震动模式

        if (soundUri != null) {
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_ALARM)
                    .build();
            notificationChannel.setSound(soundUri, audioAttributes);
        }

        assert mNotificationManager != null;
        mBuilder.setChannelId("111111");
        mNotificationManager.createNotificationChannel(notificationChannel);
    }

    //创建对象,发送的就是这个对象
    Notification build = mBuilder.build();
    mNotificationManager.notify(1, build);

}