前台服务
1.注册清单
G:\AndroidStudioProjects\AiVoikeApp\app\src\main\AndroidManifest.xml
<service android:name=".VoiceService"/> //注册
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>//权限
2.创建通知栏帮助类
G:\AndroidStudioProjects\AiVoikeApp\lib_base\src\main\java\com\example\lib_base\helper\NotificationHelper.kt
package com.example.lib_base.helper
import android.annotation.SuppressLint
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.core.app.NotificationCompat
/**
* 作者: 13967
* 时间: 2021/2/19 13:38
* 描述: 通知栏的帮助类
*/
@SuppressLint("StaticFieldLeak")
object NotificationHelper {
private lateinit var mContext: Context
private lateinit var nm : NotificationManager
private const val CHANNEL_ID = "ai_voice_service"
private const val CHANNEL_NAME = "语音服务"
//初始化帮助类
fun initHelper(mContext:Context){
this.mContext=mContext
//通知服务
nm = mContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
//创建渠道
setBindVoiceChannel()
}
//设置绑定服务的渠道
fun setBindVoiceChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
//创建渠道对象 第一个参数通道id 第二个参数显示通道名称 第三个参数渠道重要性
val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME,NotificationManager.IMPORTANCE_HIGH)
//呼吸灯
channel.enableLights(false)
//震动
channel.enableVibration(false)
//角标
channel.setShowBadge(false)
nm.createNotificationChannel(channel)//创建渠道
}
}
//绑定语音服务
fun bindVoiceService(ContentText:String): Notification {
//创建通知栏对象
val notificationCompat = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
NotificationCompat.Builder(mContext, CHANNEL_ID)
}else{
NotificationCompat.Builder(mContext)
}
//设置标题
notificationCompat.setContentTitle(CHANNEL_NAME)
//设置描述
notificationCompat.setContentText(ContentText)
//设置时间
notificationCompat.setWhen(System.currentTimeMillis())
//禁止滑动 结束服务
notificationCompat.setAutoCancel(false)
return notificationCompat.build()
}
}
后台初始化通知栏类
可能会报错 后期优化,
3.前台服务类
G:\AndroidStudioProjects\AiVoikeApp\app\src\main\java\com\example\aivoikeapp\VoiceService.kt
package com.example.aivoikeapp
import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.example.lib_base.helper.NotificationHelper
import java.security.Provider
/**
* 作者: 13967
* 时间: 2021/2/19 12:54
* 描述:
*/
class VoiceService: Service() {
override fun onBind(intent: Intent?): IBinder? {
return null//用不上说以返回空
}
/**
*START_STICKY:当系统内存不足的时候,杀掉服务,那么在系统紧张的时候才启动服务
* START_NOT_STICKY: 当系统内存不足的时候,杀掉了服务,直达下一次startServicece才启动
* START_REDELIVER_INTENT: 重新传递Intent值
* START_STICKY_COMPATIBILITY: START_STICKY兼容版本,但是它也不能保证系统killd掉服务一定能重启
*/
//后台启动
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
bindNontification()
return START_STICKY_COMPATIBILITY
}
//绑定通知栏
private fun bindNontification() {
//绑定通知栏
startForeground(1000,NotificationHelper.bindVoiceService("正在运行"))
}
}
初始化通知栏类
报错就在这里初始化
测试