欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 会展 > 微信消息语音播报秒实现

微信消息语音播报秒实现

2024/10/22 23:06:39 来源:https://blog.csdn.net/github_35581409/article/details/142975289  浏览:    关键词:微信消息语音播报秒实现

1. 监听系统消息通知

注册一个监听系统消息的服务

<serviceandroid:name=".MyNotificationListenerService"android:exported="true"android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE" ><intent-filter><action android:name="android.service.notification.NotificationListenerService" /></intent-filter></service>

实现这个服务,解析消息通知,如果是来自微信,则组装成微信消息,提取发送者,和消息内容,更新到livedata中

class MyNotificationListenerService : NotificationListenerService() {companion object{val wxMessage = MutableLiveData<WxMessage>()}override fun onNotificationPosted(sbn: StatusBarNotification) {// 捕获通知val notification = sbn.notification// 根据用户设置过滤通知println("linlian ${sbn.packageName},${sbn.notification.tickerText}")if (PACKAGE_WX == sbn.packageName) {convertToWxMessage(sbn)?.let {wxMessage.postValue(it)}}}/*** 将微信消息转换成发送者,和消息内容*/private fun convertToWxMessage(sbn: StatusBarNotification): WxMessage? {try {sbn.notification.tickerText?.let {val splits = it.split(delimiters = arrayOf(":"),ignoreCase = false,limit = 2)if (splits.size == 2) {return  WxMessage(splits[0], splits[1])}}} catch (e: Exception) {e.printStackTrace()}return null}
}

怎么启动这个消息监听服务呢

  /*显示设置界面,运行我们的应用监听服务*/private fun startNotificationSetting() {startActivity(Intent(ACTION_NOTIFICATION_LISTENER_SETTINGS));}

这时候会启动系统设置界面,我们需要允许我们的应用

如何判断系统是否允许我们监听了呢

 /*** 判断应用是否有权限*/private fun isServiceSettingEnable(): Boolean {var enable = falseval packageName = packageNameval flat: String =Settings.Secure.getString(contentResolver, "enabled_notification_listeners")if (flat != null) {enable = flat.contains(packageName)}return enable}

允许了则直接跳过,不允许的话,启动设置界面,引导用户设置。

2.语音播报

语音播报的话,主要使用TextToSpeech

初始化,设置中文

 tts = TextToSpeech(this) { status ->println("linlian status=$status")if (TextToSpeech.SUCCESS == status) {tts.setLanguage(Locale.CHINESE)}}

监听livedata

wxMessage.observe(this, object : Observer<WxMessage> {override fun onChanged(value: WxMessage) {tts.speak("收到来自${value.sender}的消息,${value.message}",TextToSpeech.QUEUE_FLUSH,null)}})

that's it 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com