`

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

详细代码在附件中
2
1
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics