安卓实现消息提醒(震动和提示音) |
您所在的位置:网站首页 › 安卓微信提示音在哪里设置 › 安卓实现消息提醒(震动和提示音) |
转自:http://blog.csdn.net/dyllove98/article/details/8799249
1.准备一个 音频文件 比如:beep.ogg。 ogg格式是声音压缩格式的一种,类似mp3这样。我们准备播放它,就产生了蜂鸣的效果。 2.为activity注册的默认 音频通道 。 activity.setVolumeControlStream(AudioManager.STREAM_MUSIC); 这里声明为 STREAM_MUSIC的通道,就是多媒体播放,注册后,我们使用 手机上的音量大小键就可以调节播放的声音大小。 如果不设定这个通道的话,我们的这个activity默认音量按钮处理将作用于 手机铃音的大小。 3.检查当前的 铃音模式,或者成为 情景模式。 说明:getRingerMode() ——返回当前的铃声模式。如RINGER_MODE_NORMAL(普通)、RINGER_MODE_SILENT(静音)、RINGER_MODE_VIBRATE(震动) //如果当前是铃音模式,则继续准备下面的 蜂鸣提示音操作,如果是静音或者震动模式。就不要继续了。因为用户选择了无声的模式,我们就也不要出声了。 AudioManager audioService = (AudioManager) activity .getSystemService(Context.AUDIO_SERVICE); if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) { shouldPlayBeep = false; } 4.初始化MediaPlayer对象,指定播放的声音 通道为 STREAM_MUSIC,这和上面的步骤一致,指向了同一个通道。MediaPlayer mediaPlayer = new MediaPlayer(); mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); 注册事件。当播放完毕一次后,重新指向流文件的开头,以准备下次播放。 // When the beep has finished playing, rewind to queue up another one. mediaPlayer .setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer player) { player.seekTo(0); } }); 设定数据源,并准备播放 AssetFileDescriptor file = activity.getResources().openRawResourceFd( R.raw.beep); try { mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength()); file.close(); mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME); mediaPlayer.prepare(); } catch (IOException ioe) { Log.w(TAG, ioe); mediaPlayer = null; } return mediaPlayer; 5.开始播放 if (playBeep && mediaPlayer != null) { mediaPlayer.start(); } -----------------------------------------------------------------
震动 这个比较简单。分两步: 1.声明权限 在AndroidManifest.xml 里写 2.获得震动服务。 Vibrator vibrator = (Vibrator) activity.getSystemService(Context.VIBRATOR_SERVICE); 3.启动震动。 vibrator.vibrate(VIBRATE_DURATION); public void playBeepSoundAndVibrate() { if (enableVibrate) { Vibrator vibrator = (Vibrator) activity .getSystemService(Context.VIBRATOR_SERVICE); //震动一次 vibrator.vibrate(VIBRATE_DURATION); //第一个参数,指代一个震动的频率数组。每两个为一组,每组的第一个为等待时间,第二个为震动时间。 // 比如 [2000,500,100,400],会先等待2000毫秒,震动500,再等待100,震动400 //第二个参数,repest指代从 第几个索引(第一个数组参数) 的位置开始循环震动。 //会一直保持循环,我们需要用 vibrator.cancel()主动终止 //vibrator.vibrate(new long[]{300,500},0); } } |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |