1

I am working on a music player and I want to create a foreground service for notification. But when I use the startForeground() method then it gives me the following error:-

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.aashushaikh.musicplayer, PID: 19998
    android.app.RemoteServiceException: Bad notification for startForeground
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2005)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

How can I resolve this error?

I have tried the following solutions but none worked for me

  1. android.app.RemoteServiceException: Bad notification for startForeground when trying to send notification from a service
  2. android.app.RemoteServiceException: Bad notification for startForeground

ApplicationClass.kt:-

class ApplicationClass: Application() {

    companion object{
        const val CHANNEL_ID = "channel1"
        const val PLAY = "play"
        const val NEXT = "next"
        const val PREVIOUS = "previous"
        const val EXIT = "exit"
        const val NOTIFICATION_ID = 0
    }

    override fun onCreate() {
        super.onCreate()
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            //Creating the channel for the notification
            val notificationChannel = NotificationChannel(CHANNEL_ID, "Now Playing Song", NotificationManager.IMPORTANCE_HIGH)
            notificationChannel.description = "This is an Important Channel for showing the songs"
            notificationChannel.lockscreenVisibility = Notification.VISIBILITY_SECRET

            //Manager is necessary to create the notification channel
            val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(notificationChannel)
        }
    }
}

MusicService.kt:-


        val notification = NotificationCompat.Builder(baseContext, ApplicationClass.CHANNEL_ID)
            .setContentTitle(PlayerActivity.musicListPlayerActivity[PlayerActivity.songPosition].title)
            .setContentText(PlayerActivity.musicListPlayerActivity[PlayerActivity.songPosition].artist)
            .setSmallIcon(R.drawable.ic_playlist)
            .setLargeIcon(BitmapFactory.decodeResource(resources, R.drawable.splash_screen))
            .setStyle(androidx.media.app.NotificationCompat.MediaStyle().setMediaSession(mediaSession.sessionToken))
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setOnlyAlertOnce(true)
            .addAction(R.drawable.ic_previous, "Previous", null)
            .addAction(R.drawable.ic_pause, "Pause", null)
            .addAction(R.drawable.ic_next, "Next", null)
            .addAction(R.drawable.ic_exit, "Exit", null)
            .build()

        startForeground(1, notification)

And I am calling this showNotification() method in the PlayerActivity.kt:- (SEE THE Method onServiceConnected and onServiceDisconnected in this file which are at the end of this file)

class PlayerActivity : AppCompatActivity(), ServiceConnection {

    private lateinit var binding: ActivityPlayerBinding

    companion object{
        lateinit var musicListPlayerActivity: ArrayList<Music>
        var songPosition: Int = 0
        var isPlaying: Boolean = false
        var musicService: MusicService? = null
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTheme(R.style.coolPink)
        binding = ActivityPlayerBinding.inflate(layoutInflater)
        setContentView(binding.root)

        //Starting the service
        val intent = Intent(this, MusicService::class.java)
        bindService(intent, this, BIND_AUTO_CREATE)
        startService(intent)

        initializeLayout()

        binding.playPauseBtnPA.setOnClickListener {
            if(isPlaying == true){
                pauseMusic()
            }else{
                playMusic()
            }
        }
        binding.previousBtnPA.setOnClickListener {
            prevNextSong(false)
        }
        binding.nextBtnPA.setOnClickListener {
            prevNextSong(true)
        }
    }

    private fun setLayout(){
        Glide.with(this).load(musicListPlayerActivity[songPosition].artUri)
            .apply (RequestOptions.placeholderOf(R.drawable.ic_noimage)) .into(binding.imagePlayer)

        binding.songNamePlayer.text = musicListPlayerActivity[songPosition].title
    }

    private fun createMediaPlayer(){
        try {
            musicService?.mediaPlayer?.let {
                musicService!!.mediaPlayer!!.reset()
                musicService!!.mediaPlayer!!.setDataSource(musicListPlayerActivity[songPosition].path)
                musicService!!.mediaPlayer!!.prepare()
                musicService!!.mediaPlayer!!.start()
                isPlaying = true
            } ?: kotlin.run {
                musicService!!.mediaPlayer = MediaPlayer()
            }
        } catch (e: Exception) {
            return
        }
    }

    private fun initializeLayout(){
        songPosition = intent.getIntExtra("index", 0)

        when(intent.getStringExtra("class")){
            "MusicAdapter" -> {
                musicListPlayerActivity = ArrayList()
                musicListPlayerActivity.addAll(MainActivity.musicListMA)
                setLayout()
            }
            "MainActivity" -> {
                musicListPlayerActivity = ArrayList()
                musicListPlayerActivity.addAll(MainActivity.musicListMA)
                musicListPlayerActivity.shuffle()
                setLayout()
            }
        }
    }

    private fun playMusic(){
        binding.playPauseBtnPA.setIconResource(R.drawable.ic_pause)
        isPlaying = true
        musicService!!.mediaPlayer!!.start()
    }
    private fun pauseMusic(){
        binding.playPauseBtnPA.setIconResource(R.drawable.ic_play)
        isPlaying = false
        musicService!!.mediaPlayer!!.pause()
    }

    private fun prevNextSong(increment: Boolean){
        if(increment){
            setSongPosition(true)
            setLayout()
            createMediaPlayer()
        }else{
            setSongPosition(false)
            setLayout()
            createMediaPlayer()
        }
    }
    private fun setSongPosition(increment: Boolean){
        if(increment){
            if(musicListPlayerActivity.size - 1 == songPosition){
                songPosition = 0
            }else{
                ++songPosition
            }
        }else{
            if(songPosition == 0){
                songPosition = musicListPlayerActivity.size - 1
            }else{
                --songPosition
            }
        }
    }

    override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
        var binder = service as MusicService.MyBinder
        musicService = binder.currentService()
        createMediaPlayer()
        musicService!!.showNotification()
    }

    override fun onServiceDisconnected(p0: ComponentName?) {
        musicService = null
    }
}
Sweta Jain
  • 3,248
  • 6
  • 30
  • 50
Aashu Shaikh
  • 21
  • 1
  • 1
  • 3

0 Answers0