Service.startForeground() issue in Android 14

72 Views Asked by At

I'm getting below the error in Android 14 target SDK version 34.

android.app.RemoteServiceException$ForegroundServiceDidNotStartInTimeException: Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{5192954 u0 in.test.myApp/.KeepAliveService} at android.app.ActivityThread.generateForegroundServiceDidNotStartInTimeException(ActivityThread.java:2315) at android.app.ActivityThread.throwRemoteServiceException(ActivityThread.java:2286) at android.app.ActivityThread.-$$Nest$mthrowRemoteServiceException(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2611) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loopOnce(Looper.java:230) at android.os.Looper.loop(Looper.java:319) at android.app.ActivityThread.main(ActivityThread.java:8913) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:608) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1103) Caused by: android.app.StackTrace: Last startServiceCommon() call for this service was made here at android.app.ContextImpl.startServiceCommon(ContextImpl.java:2023) at android.app.ContextImpl.startForegroundService(ContextImpl.java:1967) at android.content.ContextWrapper.startForegroundService(ContextWrapper.java:847) at androidx.core.content.ContextCompat$Api26Impl.startForegroundService(ContextCompat.java:933) at androidx.core.content.ContextCompat.startForegroundService(ContextCompat.java:701) at in.test.myApp.KeepAliveService.onStartCommand(KeepAliveService.kt:53)

Here is my code

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    Util.createNotificationChannel()
    val notificationIntent = Intent(this, LauncherActivity::class.java)
    val pendingIntent = PendingIntent.getActivity(
        this,
        0, notificationIntent,
        PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT
    )
    val notification = NotificationCompat.Builder(this, AppConstant.channelID)
        .setContentTitle(AppConstant.Title + " is running")
        .setContentText("Tap here to open the app")
        .setSmallIcon(R.drawable.notification_icon)
        .setContentIntent(pendingIntent)
        .build()

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) {
        startForeground(1, notification)
    } else {
        val foregroundServiceType = ServiceInfo.FOREGROUND_SERVICE_TYPE_SHORT_SERVICE 

        val startIntent = Intent(this, KeepAliveService::class.java)
        startIntent.putExtra("notification", notification)
        startIntent.putExtra("foregroundServiceType", foregroundServiceType)
        ContextCompat.startForegroundService(this, startIntent) //  Line number 53

    }
    return START_STICKY
}
0

There are 0 best solutions below