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.R 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(context.resources.getString(R.string.stop_service)) } else { serviceButtonText.set(context.resources.getString(R.string.start_service)) } } 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(context.resources.getString(R.string.stop_service)) } else { context.stopService(serviceIntent) serviceButtonText.set(context.resources.getString(R.string.start_service)) } } }