Android:自定义通知声音无法播放

Leo*_*rić 3 java audio notifications android

我已经在网站上尝试了几乎所有可用的答案,但不知怎的,我无法获得通知声音.我正在测试的当前代码是这样的(通知内置在警报接收器中):

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);
Run Code Online (Sandbox Code Playgroud)

然而,声音可以通过MediaPlayer播放,因此这里的格式不是问题.这可能与声音的长度(30秒)有关吗?谢谢您的帮助!

Muk*_*ana 5

尝试将.setSound()更改为此

.setSound(Uri.parse("android.resource://"
                            + context.getPackageName() + "/"
                            + R.raw.alert))
Run Code Online (Sandbox Code Playgroud)

希望这会奏效