Android:报警时播放自己的声音

时间:2012-08-13 07:33:48

标签: android alarmmanager

我的应用具有闹钟功能。我的要求是在闹铃响起时播放自己的声音,但我无法做到这一点。它仅在警报响起时显示通知。我要播放的声音文件位于Res中的原始文件夹中。  下面我发布我的代码:

在我的活动课程中:

Intent AlarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
        AlarmIntent.putExtra("Ringtone", 
                Uri.parse("getResources().getResourceName(R.raw.shankh_final_mid)"));
        PendingIntent Sender = PendingIntent.getBroadcast(this, 0, AlarmIntent, 0);
        AlarmManager AlmMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
        AlmMgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 
                (60 * 1000), (24 * 60 * 60 * 1000), Sender);

在接收器类中:

public void onReceive(Context context, Intent intent) { 

    Intent in = new Intent(context, SnoozeEvent.class);
    in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent Sender = PendingIntent.getActivity(context, 0, in, PendingIntent.FLAG_UPDATE_CURRENT);
    manager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
    notification = new Notification(R.drawable.icon, "Wake up alarm", System.currentTimeMillis());
    notification.setLatestEventInfo(context, "Hanuman Chalisa", "Wake Up...", Sender);
    notification.flags = Notification.FLAG_INSISTENT;
    notification.sound = (Uri)intent.getParcelableExtra("Ringtone");
    manager.notify(1, notification);  
}

4 个答案:

答案 0 :(得分:4)

您可以在套装或SD卡中设置自定义声音。只需将声音文件的路径设置为通知声音。请使用以下代码。

notification.sound = Uri.parse("android.resource://my.package.name/raw/notification");

答案 1 :(得分:1)

尝试更改这两行:

//In your activity:
AlarmIntent.putExtra("Ringtone",getResources().getResourceName(R.raw.shankh_final_mid));
....   
//In your reciever
notification.sound = (Uri)(Uri.parse(intent.getStringExtra("Ringtone")));

答案 2 :(得分:0)

尝试使用此代码发出自己的通知声音:

NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, YourActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_ONE_SHOT);
Notification note  = new Notification(R.drawable.icon, "Your Text to Show", System.currentTimeMillis());
note.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");
int nid = 123456789;
manager.notify(nid, note);

答案 3 :(得分:0)

这个答案有点过时了。

我必须打开自己的问题here才能在闹钟频道播放。

这是我的工作解决方案。

mediaPlayerScan = new MediaPlayer();
try {
  mediaPlayerScan.setDataSource(getContext(),
          Uri.parse(getString(R.string.res_path) + R.raw.scan_beep));

  if (Build.VERSION.SDK_INT >= 21) {
    mediaPlayerScan.setAudioAttributes(new AudioAttributes.Builder()
            .setUsage(AudioAttributes.USAGE_ALARM)
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .build());
  } else {
    mediaPlayerScan.setAudioStreamType(AudioManager.STREAM_ALARM);
  }
  mediaPlayerScan.prepare();
} catch (IOException e) {
  e.printStackTrace();
}