所以我正在尝试启动一个简单的前台服务,但似乎我做错了什么,或者使用片段可能有不同的方法。
这是我的服务:
class LocationForegroundService : Service() {
companion object {
private const val TRACKING_CHANNEL = "tracking_channel"
private const val TRACKING_NOTIFICATION_ID = 1
fun startService(context: Context, message: String) {
val startIntent = Intent(context, LocationForegroundService::class.java)
startIntent.putExtra("inputExtra", message)
ContextCompat.startForegroundService(context, startIntent)
}
fun stopService(context: Context) {
val stopIntent = Intent(context, LocationForegroundService::class.java)
context.stopService(stopIntent)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val input = intent?.getStringExtra("inputExtra")
createNotificationChannel()
val notificationIntent = Intent(this, RiderManagementActivity::class.java)
val pendingIntent = PendingIntent.getActivity(
this,
0,
notificationIntent,
0
)
val notification = NotificationCompat.Builder(this, TRACKING_CHANNEL)
.setContentTitle("Test")
.setContentText(input)
.setContentIntent(pendingIntent)
.build()
startForeground(TRACKING_NOTIFICATION_ID, notification)
return START_STICKY
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationChannel = NotificationChannel(
TRACKING_CHANNEL,
"Foreground Location Channel",
NotificationManager.IMPORTANCE_DEFAULT
)
val manager = getSystemService(NotificationManager::class.java)
manager.createNotificationChannel(notificationChannel)
}
}
override fun onBind(intent: Intent?): IBinder? = null
}
这是在片段中调用服务的方式:
binding.btnPlayPause.setOnClickListener {
val intent = Intent(requireContext(), LocationForegroundService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
requireContext().showShortToast("track")
LocationForegroundService.startService(requireContext(), "Testing")
} else {
requireActivity().startService(intent)
}
}
并且我已经在清单文件中声明:
...
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
...
<application
.../>
<service
android:name=".util.LocationForegroundService"
/>
所以我一定遗漏了一些东西,因为我收到了这个错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.quicktendr.mgmt.androidApp, PID: 12693
android.app.RemoteServiceException: Bad notification for startForeground
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1872)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7050)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
更新: 我创建了另外两个项目并测试了相同的服务。 1 android native 和 kotlin multiplataform 中的另一个与原始版本一样,在 android 上运行良好,但 kotlin multiplataform 我得到了相同的错误。
答案 0 :(得分:1)
据我所知,您需要在尝试启动前台服务(>= API 27)之前创建通知渠道。
因此,尝试在您的服务中创建频道是行不通的。
答案 1 :(得分:1)
我通过向通知添加图标解决了这个错误,但很奇怪只是在 kotlin 多平台项目上崩溃,而在 android 项目上没有。