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

import android.app.Activity
import android.app.AlertDialog
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.content.DialogInterface
import android.content.Intent
import android.databinding.ObservableField
import android.net.Uri
import android.provider.Settings
import android.view.View
import jackall.moncalc.R
import jackall.moncalc.service.MainService
import jackall.moncalc.utils.RuntimePermissionUtil
import jackall.moncalc.utils.ServiceUtil.Companion.isMainServiceRunning


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

    init {
        if (isMainServiceRunning(activity)) {
            serviceButtonText.set(activity.resources.getString(R.string.stop_service))
        } else {
            serviceButtonText.set(activity.resources.getString(R.string.start_service))
        }
    }

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

    fun onClickServiceButton(view: View) {
        if (RuntimePermissionUtil.checkOverlayPermission(activity)) {
            if (!isMainServiceRunning(activity)) {
                activity.startService(serviceIntent)
                serviceButtonText.set(activity.resources.getString(R.string.stop_service))
            } else {
                activity.stopService(serviceIntent)
                serviceButtonText.set(activity.resources.getString(R.string.start_service))
            }
        } else {
            AlertDialog.Builder(activity)
                    .setMessage("常駐機能を使用するには権限の許可が必要です。")
                    .setPositiveButton("設定", DialogInterface.OnClickListener { dialog, which ->
                        val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:jackall.moncalc"))
                        activity.startActivityForResult(intent, 2)
                    })
                    .setNegativeButton("許可しない", null)
                    .show()
        }
    }
}