簡體   English   中英

Android:自定義通知聲音無法播放

[英]Android: Custom notification sound not playing

我已經在網站上嘗試了幾乎所有可用的答案,但不知怎的,我無法獲得通知聲音。 我正在測試的當前代碼是這樣的(通知內置在警報接收器中):

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秒)有關嗎? 謝謝您的幫助!

嘗試將.setSound()更改為此

.setSound(Uri.parse("android.resource://"
                            + context.getPackageName() + "/"
                            + R.raw.alert))

希望這會奏效

如果穆克什的正確答案不適合你,請在這里閱讀 !!

從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,但仍然無法正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM