1. 监听系统消息通知
注册一个监听系统消息的服务
<service
android: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中
Kotlin
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
}
}
怎么启动这个消息监听服务呢
Kotlin
/*
显示设置界面,运行我们的应用监听服务
*/
private fun startNotificationSetting() {
startActivity(Intent(ACTION_NOTIFICATION_LISTENER_SETTINGS));
}
这时候会启动系统设置界面,我们需要允许我们的应用
如何判断系统是否允许我们监听了呢
Kotlin
/**
* 判断应用是否有权限
*/
private fun isServiceSettingEnable(): Boolean {
var enable = false
val packageName = packageName
val flat: String =
Settings.Secure.getString(contentResolver, "enabled_notification_listeners")
if (flat != null) {
enable = flat.contains(packageName)
}
return enable
}
允许了则直接跳过,不允许的话,启动设置界面,引导用户设置。
2.语音播报
语音播报的话,主要使用TextToSpeech
初始化,设置中文
Kotlin
tts = TextToSpeech(this) { status ->
println("linlian status=$status")
if (TextToSpeech.SUCCESS == status) {
tts.setLanguage(Locale.CHINESE)
}
}
监听livedata
Kotlin
wxMessage.observe(this, object : Observer<WxMessage> {
override fun onChanged(value: WxMessage) {
tts.speak(
"收到来自${value.sender}的消息,${value.message}",
TextToSpeech.QUEUE_FLUSH,
null
)
}
})
that's it