如何在Android中播放通知声音?

时间:2013-01-03 11:03:39

标签: android

我是Android的新手,我尝试通过声音播放声音,但它无法在模拟器上运行。请帮帮我。

public class OneShotAlarm extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, R.string.one_shot_received, Toast.LENGTH_SHORT).show();

        buildNotification(context);

    }


    @SuppressLint("NewApi")
    private void buildNotification(Context context){
          NotificationManager notificationManager 
          = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
          Notification.Builder builder = new Notification.Builder(context);

          Intent intent = new Intent(context, MainActivity.class);
          PendingIntent pendingIntent 
          = PendingIntent.getActivity(context, 0, intent, 0);

          builder
          .setSmallIcon(R.drawable.ic_launcher)
          .setContentTitle("ContentTitle")
          .setContentText("ContentText")
          .setContentInfo("ContentInfo")
          .setTicker("Ticker")
          .setLights(0xFFFF0000, 500, 500) //setLights (int argb, int onMs, int offMs)
          .setContentIntent(pendingIntent)
          .setSound(Uri.parse("android.resource://com.vatshal.VSAlarm/" + R.raw.satinder))
          .setAutoCancel(true);

          Notification notification = builder.build();
          //notification.sound = Uri.parse("android.resource://com.vatshal.VSAlarm/" + R.raw.satinder); 
          //notification.defaults |= Notification.DEFAULT_SOUND;

          notificationManager.notify(R.drawable.notification_warning, notification);
         }
}

2 个答案:

答案 0 :(得分:2)

确保资源中有声音

try {
        MediaPlayer mediaPlayer = MediaPlayer.create(context,                 R.raw.sound);
        mediaPlayer.start();
    } catch (Exception ex) {

    }

答案 1 :(得分:0)

我用过

.setSound(Uri.parse(“android.resource://com.vatshal.VSAlarm/”+ R.raw.satinder))

设置音频路径的正确语法是放在“raw”文件夹中的“satinder”名称吗?