2022-07-23 19:11:57 +05:30
|
|
|
package com.github.libretube.util
|
|
|
|
|
2022-11-29 19:59:26 +05:30
|
|
|
import android.app.ActivityManager
|
2022-07-23 19:11:57 +05:30
|
|
|
import android.content.Context
|
|
|
|
import android.content.Intent
|
2022-08-21 14:40:57 +05:30
|
|
|
import android.os.Build
|
2022-09-08 23:49:44 +05:30
|
|
|
import com.github.libretube.constants.IntentData
|
2022-07-23 19:11:57 +05:30
|
|
|
import com.github.libretube.services.BackgroundMode
|
|
|
|
|
2022-08-08 14:13:46 +05:30
|
|
|
/**
|
|
|
|
* Helper for starting a new Instance of the [BackgroundMode]
|
|
|
|
*/
|
2022-07-23 19:11:57 +05:30
|
|
|
object BackgroundHelper {
|
2022-11-29 19:59:26 +05:30
|
|
|
|
|
|
|
/**
|
|
|
|
* Start the foreground service [BackgroundMode] to play in background. [position]
|
|
|
|
* is seek to position specified in milliseconds in the current [videoId].
|
|
|
|
*/
|
2022-07-23 19:11:57 +05:30
|
|
|
fun playOnBackground(
|
|
|
|
context: Context,
|
|
|
|
videoId: String,
|
2022-08-08 14:13:46 +05:30
|
|
|
position: Long? = null,
|
|
|
|
playlistId: String? = null
|
2022-07-23 19:11:57 +05:30
|
|
|
) {
|
2022-08-08 14:13:46 +05:30
|
|
|
// create an intent for the background mode service
|
2022-07-23 19:11:57 +05:30
|
|
|
val intent = Intent(context, BackgroundMode::class.java)
|
2022-09-08 23:49:44 +05:30
|
|
|
intent.putExtra(IntentData.videoId, videoId)
|
|
|
|
if (playlistId != null) intent.putExtra(IntentData.playlistId, playlistId)
|
2022-07-23 19:11:57 +05:30
|
|
|
if (position != null) intent.putExtra("position", position)
|
2022-08-08 14:13:46 +05:30
|
|
|
|
|
|
|
// start the background mode as foreground service
|
2022-08-21 14:40:57 +05:30
|
|
|
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
|
|
|
|
context.startForegroundService(intent)
|
|
|
|
} else {
|
|
|
|
context.startService(intent)
|
|
|
|
}
|
2022-07-23 19:11:57 +05:30
|
|
|
}
|
2022-11-29 19:59:26 +05:30
|
|
|
|
|
|
|
/**
|
|
|
|
* Stop the [BackgroundMode] service if it is running.
|
|
|
|
*/
|
|
|
|
fun stopBackgroundPlay(context: Context) {
|
|
|
|
if (!isServiceRunning(context, BackgroundMode::class.java)) return
|
|
|
|
|
|
|
|
// Intent to stop background mode service
|
|
|
|
val intent = Intent(context, BackgroundMode::class.java)
|
|
|
|
context.stopService(intent)
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Check if the given service as [serviceClass] is currently running.
|
|
|
|
*/
|
|
|
|
fun isServiceRunning(context: Context, serviceClass: Class<*>): Boolean {
|
|
|
|
val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
|
|
|
|
@Suppress("DEPRECATION")
|
|
|
|
for (service in manager.getRunningServices(Int.MAX_VALUE)) {
|
|
|
|
if (serviceClass.name == service.service.className) {
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
2022-07-23 19:11:57 +05:30
|
|
|
}
|