android - 通知自定义声音和振动不起作用?
问题描述
我有一个接收通知的应用程序,一切正常。但是,自定义声音和振动不起作用。我正在 Android 9 pie 上对其进行测试。
Uri sound = Uri.parse("android.resource://" +getApplicationContext().getPackageName()+ "/" +R.raw.siren); //ContentResolver.SCHEME_ANDROID_RESOURCE +
String NOTIFICATION_CHANNEL_ID = "com.example.bantay.bantay.test";
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setWhen(System.currentTimeMillis());
notificationBuilder.setSmallIcon(R.drawable.marikinalogo);
notificationBuilder.setContentTitle(title);
notificationBuilder.setContentText(body);
notificationBuilder.setSound(sound);
notificationBuilder.setVibrate(new long[]{500, 1000, 500, 1000});
if(title.toLowerCase().contains("1")){
notificationBuilder.setContentIntent(pendingIntent);
}
else{
notificationBuilder.setContentIntent(pendingIntent3);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "Notification", NotificationManager.IMPORTANCE_HIGH);
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{500, 1000, 500, 1000});
notificationChannel.setSound(sound, audioAttributes);
notificationManager.createNotificationChannel(notificationChannel);
}
notificationManager.notify(0, notificationBuilder.build());
我不知道我的错误。NOTIFICATION_CHANNEL_ID 是否影响通知的行为?
解决方案
我正在使用MediaPlayer
自定义声音。这对我来说很好用。这适用于所有设备。
private MediaPlayer player;
播放自定义声音:
try {
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.siren);
player = MediaPlayer.create(this, uri);
player.setLooping(true); // This will play sound in repeatable mode.
player.start();
// mBuilder.setSound(uri);
} catch (Exception e) {
e.printStackTrace();
}
对于停止声音:
if (player != null)
player.stop();
这对我有用。希望这也能帮助你。
推荐阅读
- python-3.x - 据我了解,缓冲模式 MPI 不起作用
- mysql - mysql #1241 中的错误 — 操作数必须包含 1 列。我如何提出替代工作请求?
- mysql - 如何使用 ISEMPTY 功能
- http - 使用 POST 方法的错误结果
- typescript - TypeScript 接口不限制属性的数量吗?
- javascript - Django 注册表单中的 Javascript 表单验证
- autodesk-forge - 如何在房间元素内创建房间名称文本?
- html - jpg图像显示问题
- unity3d - Read groupshared variables back to cpu memory
- javascript - 没有useEffect做api调用不正确吗?