Android/Android 일반

서비스 예제(kotlin)

lipnus 2019. 2. 15. 10:13
반응형


1.MainActivity.kt

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()
}



2.RandomNumberService.kt

class RandomNumberService : Service() {

private lateinit var mHandler: Handler
private lateinit var mRunnable: Runnable

override fun onBind(intent: Intent): IBinder? {
throw UnsupportedOperationException("Not yet implemented")
}

override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
// Send a notification that service is started
Log.d("SSS", "Service onStartCommand()")

// Do a periodic task
mHandler = Handler()
mRunnable = Runnable { showRandomNumber() }
mHandler.postDelayed(mRunnable, 5000)

return Service.START_STICKY
}

override fun onDestroy() {
super.onDestroy()
Log.d("SSS", "Service onDestroy()")
mHandler.removeCallbacks(mRunnable)
}

// Custom method to do a task
private fun showRandomNumber() {
val rand = Random()
val number = rand.nextInt(100)
Log.d("SSS", "showRandomNumber():$number")

mHandler.postDelayed(mRunnable, 5000)
}
}


반응형

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

Country Picker 라이브러리  (0) 2019.02.21
죽지 않는 서비스  (0) 2019.02.15
SMS Retriever API - 2  (0) 2019.01.20
SMS Retriever API - 1  (0) 2019.01.20
Hash Code 구하는 코드  (0) 2019.01.20