Newer
Older
MonCalc / app / src / main / kotlin / jackall / moncalc / activity / MainActivity.kt
package jackall.moncalc.activity

import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import jackall.moncalc.R
import jackall.moncalc.service.MainService
import kotlinx.android.synthetic.main.activity_main.*


class MainActivity : AppCompatActivity() {

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

        // TODO:レイアウトを決めてdatbinding,viewModelProvidersを有効にする
        val intent = Intent(this, MainService::class.java)

        start_service_btn.setOnClickListener {
            if (!isMainServiceRunning())
                startService(intent)
        }

        stop_service_btn.setOnClickListener {
            if (isMainServiceRunning())
                stopService(intent)
        }
    }

    private fun isMainServiceRunning(): Boolean {
        val manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        for (serviceInfo in manager.getRunningServices(Integer.MAX_VALUE)) {
            if (MainService::class.java.getName() == serviceInfo.service.className) {
                return true
            }
        }
        return false
    }
}