android 通知 和 通知的声音 (附源码)

完成后的效果:运行例子,会在手机的状态栏显示一个通知的提示图案,并有你自己定义的通知声音,然后当点击了这个事件,跳转到另一个activity中,同时通知的提示图案消失.

1.获取通知管理器

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

2.创建一个通知,指定其图标和标题,创建新的activity,发布通知

int icon = android.R.drawable.stat_notify_chat;
long when = System.currentTimeMillis();
// 第一个参数为图标,第二个参数为标题,第三个为通知时间
Notification notification = new Notification(icon, null, when);
Intent openintent = new Intent(this, OtherActivity.class);
// 当点击消息时就会向系统发送openintent意图
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
openintent, 0);
notification.setLatestEventInfo(this, "标题", "内容", contentIntent);

mNotificationManager.notify(0, notification);

3.新建一个方法 用来播放提示音

private MediaPlayer ring() throws Exception, IOException {
// TODO Auto-generated method stub
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
MediaPlayer player = new MediaPlayer();
player.setDataSource(this, alert);
final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
if (audioManager.getStreamVolume(AudioManager.STREAM_NOTIFICATION) != 0) {
player.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
player.setLooping(true);
player.prepare();
player.start();
}
return player;
}

注意事项:本实例在g3测试通过,但是模拟器上不行 报空指针 因为没有指定的音频文件,报类似这样的错误 12-22 02:26:09.734: ERROR/MediaPlayerService(34): Couldn't open fd for content://settings/system/alarm_alert

详细代码在附件中
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值