我在网站上尝试了几乎所有可用的答案,但不知怎的,我无法获得通知声音。我正在测试的当前代码是这样的(通知是在报警接收器中构建的):
public class AlarmReceiver extends BroadcastReceiver {
private static final int NOTIFICATION_ID = 0;
@Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(context.getString(R.string.app_name))
.setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, MainActivity_.class), 0))
.setContentText("temporary text")
.setAutoCancel(true)
.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
+ "://" + context.getPackageName() + "/raw/alert"))
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_stat_notification);
Notification notification = builder.build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notification);
然而,声音可以通过MediaPlayer播放,因此这里的格式不是问题。 这可能与声音的长度(30秒)有关吗? 谢谢你的帮助!
答案 0 :(得分:5)
尝试将.setSound()更改为此
.setSound(Uri.parse("android.resource://"
+ context.getPackageName() + "/"
+ R.raw.alert))
希望这会起作用
答案 1 :(得分:1)
请在这里阅读如果穆克什的正确答案对您不起作用!!
Mukesh发表的答案是正确的,但对我而言,直到我发现我将通知配置错误才开始工作! (或者有一个Android BUG)
此代码段不起作用
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder( context )
.setDefaults( DEFAULT_VIBRATE | FLAG_SHOW_LIGHTS )
.setContentTitle( title )
.setContentText( message )
.setSound( "android.resource://"
+ context.getPackageName() + "/"
+ R.raw.alert)).build();
-
此代码段工作
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder( context )
.setContentTitle( title )
.setContentText( message )
.setSound( "android.resource://"
+ context.getPackageName() + "/"
+ R.raw.alert)).build();
-
.setDefaults( DEFAULT_VIBRATE | FLAG_SHOW_LIGHTS )
观察:就像你看到上面一行我没有使用constanst DEFAULT_SOUND,但仍然无法正常工作。