如何在android中设置自定义声音通知

use*_*434 46 android

我将mp3(kalimba.mp3)文件复制到raw文件夹中的res文件夹中.但是当触发通知时,它会产生默认声音.

这是我发出通知的方式:

protected void GenerateNotify() {

    NotificationManager myNotificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);  
    Notification notification=new Notification(android.R.drawable.ic_btn_speak_now,"hi",100);
    Intent intent=new Intent(getApplicationContext(),as.class);
    PendingIntent contentintent=PendingIntent.getBroadcast(getApplicationContext(),0, intent, 0);
    notification.setLatestEventInfo(getApplicationContext(), "Hi","date", contentintent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.sound = Uri.parse("android.resource://com.example.serviceproject/" + R.raw.kalimba);
    myNotificationManager.notify(NOTIFICATION_ID,notification);
}
Run Code Online (Sandbox Code Playgroud)

Quo*_*oon 112

notification.sound = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notifysnd);
notification.defaults = Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE;
Run Code Online (Sandbox Code Playgroud)

如果定义了DEFAULT_SOUND,则默认声音会覆盖任何声音

  • 如果我不写`notification.defaults`那么播放自定义声音的可能性是多少? (2认同)

dsa*_*ler 17

R.raw.kalimba是整数资源ID; 你想要声音资源的名称Uri.所以尝试:

notification.sound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
        + "://" + getPackageName() + "/raw/kalimba");
Run Code Online (Sandbox Code Playgroud)


小智 5

尝试这个:

Uri sound = Uri.parse("android.resource://" + context.getPackageName() + "/raw/notifysnd);
notification.setSound(sound);
Run Code Online (Sandbox Code Playgroud)