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 com.google.gson.Gson import com.google.gson.stream.JsonReader import jackall.moncalc.Const import jackall.moncalc.R import jackall.moncalc.common.PreferenceKeys import jackall.moncalc.common.PreferenceNames import jackall.moncalc.db.FruitRealmHelper import jackall.moncalc.db.GradeRealmHelper import jackall.moncalc.db.TempleRealmHelper import jackall.moncalc.service.MainService import jackall.moncalc.utils.MySharedPref import jackall.moncalc.vo.MonstData import kotlinx.android.synthetic.main.activity_main.* import java.io.InputStreamReader class MainActivity : AppCompatActivity() { val mySharedPref by lazy { MySharedPref(this, PreferenceNames.CONFIG) } val fruitRealmHelper by lazy { FruitRealmHelper() } val templeRealmHelper by lazy { TempleRealmHelper() } val gradeRealmHelper by lazy { GradeRealmHelper() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // TODO:レイアウトを決めてdatbinding,viewModelProvidersを有効にする val intent = Intent(this, MainService::class.java) if ((mySharedPref.getValue(PreferenceKeys.QUESTDATAVERSION, Int::class.java, -1) as Int) < Const.questDataVersion) { val inputStream = assets.open("data.json") val jsonReader = JsonReader(InputStreamReader(inputStream)) val monstData = Gson().fromJson<MonstData>(jsonReader, MonstData::class.java) fruitRealmHelper.update(monstData.fruit) templeRealmHelper.update(monstData.temple) gradeRealmHelper.update(monstData.grade) mySharedPref.putValue(PreferenceKeys.QUESTDATAVERSION, Int::class.java, Const.questDataVersion) println("db update") } start_service_btn.setOnClickListener { if (!isMainServiceRunning()) startService(intent) } stop_service_btn.setOnClickListener { if (isMainServiceRunning()) stopService(intent) } } override fun onDestroy() { super.onDestroy() fruitRealmHelper.close() templeRealmHelper.close() } 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 } }