Android消息提示音和振动管理类

Android消息提示音和振动管理类

主要参考ZXing中的声音管理类BeepManager中集成了声音播放和振动

参考的文章在末尾,有兴趣的可以也读一下

设置一些默认的全局参数

  • 设置音量
  • 设置振动时长

代码

/**
 * 类描述:消息提示音和振动管理类
* 创建人:吴冬冬
* 创建时间:2019/1/28 15:15
*/ class BeepAndVibrateManager constructor(context: Context) : MediaPlayer.OnErrorListener, Closeable { private var mContext: WeakReference? = null private var mMediaPlayer: MediaPlayer? = null private var mPlayBeep = false companion object { private const val BEEP_VOLUME = 0.1F; private const val VIBRATE_DURATION = 200L; } init { mContext = WeakReference(context) mMediaPlayer = null initBeep() } private fun initBeep() { val context = mContext?.get() ?: return mPlayBeep = shouldBeep(context) //设置声音基本设置 if (mPlayBeep) { mMediaPlayer = buildMediaPlayer(context) } } /** * 播放和振动调用方法 */ @Synchronized @JvmOverloads fun playBeepSoundAndVibrate(isBeepSound: Boolean = true, isVibrate: Boolean = true ) { val context = mContext?.get() ?: return if (isBeepSound) { if (shouldBeep(context)) { if (mMediaPlayer == null) { mMediaPlayer = buildMediaPlayer(context) } mMediaPlayer!!.start() } } if (isVibrate) { val vibrator = context.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator vibrator.vibrate(VIBRATE_DURATION) } } private fun shouldBeep(context: Context): Boolean { val audioService = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager //如果手机不是普通模式就不让其有声音 return audioService.ringerMode == AudioManager.RINGER_MODE_NORMAL } private fun buildMediaPlayer(context: Context): MediaPlayer { val mediaPlayer = MediaPlayer() //Z Xing 声音文件是放在raw下的 //val file = context.resources.openRawResource(R.raw.beep) //我这里直接用系统默认声音提示 mediaPlayer.setDataSource(context, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)) mediaPlayer.setOnErrorListener(this) //设置该Activity中音量控制键控制的音频流 mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)//媒体音量 mediaPlayer.isLooping = false //左右声道声音大小 mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME) mediaPlayer.prepare() return mediaPlayer } override fun onError(mp: MediaPlayer?, what: Int, extra: Int): Boolean { if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) { // we are finished, so put up an appropriate error toast if required and finish //context.finish() } else { // possibly media player error, so release and recreate close() initBeep() } return true } @Synchronized override fun close() { if (mMediaPlayer != null) { mMediaPlayer?.stop() mMediaPlayer?.release() mMediaPlayer = null } } }

参考文章

  • ZXing---BeepManger
  • Android中手机震动的设置(Vibrator)的步骤
  • AudioManager
  • android音量控制setVolumeControlStream
  • android 震动和提示音
  • Android开发(20)蜂鸣提示音和震动
  • Android开发 震动 提示音

你可能感兴趣的:(Android消息提示音和振动管理类)