Android消息提示音和振动管理类
主要参考ZXing中的声音管理类
BeepManager
中集成了声音播放和振动参考的文章在末尾,有兴趣的可以也读一下
设置一些默认的全局参数
- 设置音量
- 设置振动时长
代码
/**
* 类描述:消息提示音和振动管理类<br/>
* 创建人:吴冬冬<br/>
* 创建时间:2019/1/28 15:15<br/>
*/
class BeepAndVibrateManager constructor(context: Context) : MediaPlayer.OnErrorListener, Closeable {
private var mContext: WeakReference<Context>? = 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
}
}
}
网友评论