Android/Android 일반

서비스 실행유무 확인

lipnus 2019. 2. 25. 13:41
반응형

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

// Variable to hold service class name
val serviceClass = RandomNumberService::class.java

// Initialize a new Intent instance
val intent = Intent(applicationContext, serviceClass)


// Button to start the service
button_start.setOnClickListener{
// If the service is not running then start it
if (!isServiceRunning(serviceClass)) {
// Start the service
startService(intent)
} else {
toast("Service already running.")
}
}


// Button to stop the service
button_stop.setOnClickListener{
// If the service is not running then start it
if (isServiceRunning(serviceClass)) {
// Stop the service
stopService(intent)
} else {
toast("Service already stopped.")
}
}


// Get the service status
button_stats.setOnClickListener{
if (isServiceRunning(serviceClass)) {
toast("Service is running.")
} else {
toast("Service is stopped.")
}
}
}


// Custom method to determine whether a service is running
private fun isServiceRunning(serviceClass: Class<*>): Boolean {

val activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager

// Loop through the running services
for (service in activityManager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.name == service.service.className) {
// If the service is running then return true
return true
}
}
return false
}
}



// Extension function to show toast message
fun Context.toast(message:String){
Toast.makeText(applicationContext,message,Toast.LENGTH_SHORT).show()
}


반응형

'Android > Android 일반' 카테고리의 다른 글

그림자 나인패치 생성사이트  (0) 2019.03.05
[Kotlin] 소스코드로 TextView 색상 바꾸기  (0) 2019.02.28
Country Picker 라이브러리  (0) 2019.02.21
죽지 않는 서비스  (0) 2019.02.15
서비스 예제(kotlin)  (1) 2019.02.15