Created
November 2, 2022 14:19
-
-
Save alokomkar/b9708d1318b1b571cd3f4788eaa42e85 to your computer and use it in GitHub Desktop.
Step 3 : Foreground service : AudioForegroundLoopService
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import android.app.Service | |
| import android.content.Intent | |
| import android.media.MediaPlayer | |
| import android.os.Build | |
| import android.os.IBinder | |
| import com.alokomkar.helper.NotificationHelper | |
| import com.alokomkar.javacollections.R | |
| class AudioForegroundLoopService: Service() { | |
| private val notificationHelper: NotificationHelper by lazy { | |
| NotificationHelper(this) | |
| } | |
| private val mediaPlayer: MediaPlayer by lazy { | |
| MediaPlayer.create(this, R.raw.sample_audio) | |
| } | |
| // execution of service will start | |
| // on calling this method | |
| override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { | |
| when(intent?.action) { | |
| ServiceAction.START_ACTION.value -> startPlayback() | |
| ServiceAction.STOP_ACTION.value -> stopService() | |
| else -> return START_NOT_STICKY | |
| } | |
| return START_NOT_STICKY | |
| } | |
| private fun startPlayback() { | |
| mediaPlayer.apply { | |
| isLooping = true | |
| start() | |
| } | |
| // publish notification | |
| startForeground(NotificationHelper.NOTIFICATION_ID, notificationHelper.getNotification()) | |
| } | |
| // No binding allowed with any UI component | |
| override fun onBind(intent: Intent?): IBinder? { | |
| return null | |
| } | |
| private fun stopService() { | |
| if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { | |
| stopForeground(true) | |
| } else { | |
| stopSelf() | |
| } | |
| } | |
| // execution of the service will | |
| // stop on calling this method | |
| override fun onDestroy() { | |
| super.onDestroy() | |
| mediaPlayer.stop() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment