PlayService.kt 1.54 KB
Newer Older
konghaorui committed
1
package com.ydl.media.audio
konghaorui committed
2 3 4 5 6 7 8

import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Binder
import android.os.IBinder
import android.util.Log
konghaorui committed
9 10 11
import com.ydl.media.audio.constants.Extras
import com.ydl.media.audio.manager.MediaSessionManager
import com.ydl.media.audio.manager.NotifyManager
konghaorui committed
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

/**
 * Created by haorui on 2019-10-27 .
 * Des: 音乐播放后台服务
 */
class PlayService : Service() {

    inner class PlayBinder : Binder() {
        val service: PlayService
            get() = this@PlayService
    }

    override fun onCreate() {
        super.onCreate()
        Log.i(TAG, "onCreate: " + javaClass.simpleName)
        AudioPlayer.get().init(this)
        MediaSessionManager.get().init(this)
        NotifyManager.get().init(this)
    }

    override fun onBind(intent: Intent): IBinder? {
        return PlayBinder()
    }

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        if (intent != null && intent.action != null) {
            when (intent.action) {
                Extras.ACTION_STOP -> stop()
            }
        }
        return Service.START_NOT_STICKY
    }

    private fun stop() {
        AudioPlayer.get().stopPlayer()
        NotifyManager.get().cancelAll()
    }

    companion object {
        private val TAG = "Service"

        fun startCommand(context: Context, action: String) {
            val intent = Intent(context, PlayService::class.java)
            intent.action = action
            context.startService(intent)
        }
    }
}