Newer
Older
MonCalc / app / src / main / kotlin / jackall / moncalc / viewmodel / MainViewModel.kt
package jackall.moncalc.viewmodel

import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.content.Context
import android.content.Intent
import android.databinding.ObservableField
import android.view.View
import jackall.moncalc.service.MainService
import jackall.moncalc.utils.ServiceUtil.Companion.isMainServiceRunning

/**
 * MainActivityのViewModel.
 *
 * Created by matsumoto_k on 2017/11/01.
 */
class MainViewModel(val context: Context) : LifecycleViewModel() {
    val serviceButtonText = ObservableField<String>("")
    val serviceIntent by lazy {
        val intent = Intent(context, MainService::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        intent
    }

    init {
        if (isMainServiceRunning(context)) {
            serviceButtonText.set("常駐終了")
        } else {
            serviceButtonText.set("常駐開始")
        }
    }

    class Factory(val context: Context) : ViewModelProvider.NewInstanceFactory() {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            return MainViewModel(context) as T
        }
    }

    fun onClickServiceButton(view: View) {
        if (!isMainServiceRunning(context)) {
            context.startService(serviceIntent)
            serviceButtonText.set("常駐終了")
        } else {
            context.stopService(serviceIntent)
            serviceButtonText.set("常駐開始")
        }
    }
}