fix: Task 9 완료 - LocationUpdateService 스레드 풀 누수 제거 및 예외/동기화 보강

- LocationUpdateService.kt pushLocation():
  * 매 호출마다 생성되던 Executors.newSingleThreadScheduledExecutor() 제거 -> 공유 locationScope(Dispatchers.IO + SupervisorJob) + delay(5000L) 전환
  * addresses.first() -> addresses.firstOrNull() ?: return@getFromLocation 으로 빈 목록 예외 방어
  * Realm writeBlocking 호출부 try-catch 추가
  * 공용 NetworkClient.client 및 Response.use {} 적용으로 OkHttp 커넥션 누수 제거
  * lastWeather 갱신 시 synchronized(lastWeather) 적용
- TODO.md: 2-2, 3-1, 3-2, 4-2 항목 완료 처리
- 검증: ./gradlew :app:compileDebugKotlin 빌드 성공 확인 (1s)
This commit is contained in:
2026-11-16 11:17:58 +09:00
parent 48d279afc2
commit 2dacf5fcd8
2 changed files with 60 additions and 76 deletions
@@ -35,11 +35,15 @@ import java.util.Base64
import java.util.Locale
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import kotlinx.coroutines.launch
class LocationUpdateService : Service(), LocationListener {
companion object {
private val locationScope = kotlinx.coroutines.CoroutineScope(
kotlinx.coroutines.Dispatchers.IO + kotlinx.coroutines.SupervisorJob()
)
var longitude: Double = 0.0
var lastWeather = mutableListOf<String>()
var latitude: Double = 0.0
@@ -48,104 +52,84 @@ class LocationUpdateService : Service(), LocationListener {
val geocoder = Geocoder(context, Locale.getDefault())
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
geocoder.getFromLocation(lat, long, 1) { addresses ->
addresses.first()?.let {
addresses.get(0)
WorkersDb.getRealm()?.apply {
LocationLog().let { loc ->
loc.fillData(it)
val address = addresses.firstOrNull() ?: return@getFromLocation
WorkersDb.getRealm()?.apply {
LocationLog().let { loc ->
loc.fillData(address)
var list = query<LocationLog>().query("userId == $0", PrefString.telegramMyId.get("")).sort("time", Sort.DESCENDING).find()
val post = (list.size == 0 || (list.size > 0 && list.first().time < (System.currentTimeMillis() - (1000L * 60L * 5L))))
//&& inRangeLocation(lat,long,50) == false
val list = query<LocationLog>().query("userId == $0", PrefString.telegramMyId.get("")).sort("time", Sort.DESCENDING).find()
val post = (list.size == 0 || (list.size > 0 && list.first().time < (System.currentTimeMillis() - (1000L * 60L * 5L))))
try {
writeBlocking {
if (post) {
loc.userId = PrefString.telegramMyId.get("")
copyToRealm(loc)
}
}
// post = true
// post.letTrue {
Executors.newSingleThreadScheduledExecutor().schedule({
try {
val url = PrefString.locationApi.get()
if (url.length > 10) {
val client = OkHttpClient.Builder()
.connectionPool(ConnectionPool(5, 60, TimeUnit.SECONDS))
.build()
} catch (e: Exception) {
e.printStackTrace()
}
// GET 요청 객체 생성
val builder: Request.Builder = Request.Builder().url(url)
.addHeader("Content-Type", "application/json").get()
builder.method(
val locJsonBytes = Gson().toJson(loc).toByteArray()
locationScope.launch {
kotlinx.coroutines.delay(5000L)
try {
val url = PrefString.locationApi.get()
if (url.length > 10) {
val request = Request.Builder()
.url(url)
.addHeader("Content-Type", "application/json")
.method(
"POST", RequestBody.create(
"application/text".toMediaTypeOrNull(),
Base64.getEncoder().encode(
Gson().toJson(loc).toByteArray()
)
Base64.getEncoder().encode(locJsonBytes)
)
)
val request: Request = builder.build()
.build()
// Blog.LOGE("telegram before request ")
// OkHttp 클라이언트로 GET 요청 객체 전송
val response: Response = client.newCall(request).execute()
if (response.isSuccessful) {
// 응답 받아서 처리
val body: ResponseBody? = response.body
if (body != null) {
// Blog.LOGE("Location >>> ${body.string()}")
}
} else Blog.LOGE("telegram Error Occurred")
bums.lunatic.launcher.utils.NetworkClient.client.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
Blog.LOGE("telegram Error Occurred: ${response.code}")
}
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
}, 5, TimeUnit.SECONDS)
} catch (e: Exception) {
e.printStackTrace()
}
}
Blog.LOGE("addresses ${addresses.first()}")
Executors.newSingleThreadScheduledExecutor().schedule({
try {
val url = "https://api.weatherapi.com/v1/current.json?key=${PrefString.weatherApiKey.get()}&q=${lat},${long}&aqi=no"
if (url.length > 10) {
val client = OkHttpClient.Builder()
.connectionPool(ConnectionPool(5, 60, TimeUnit.SECONDS))
.build()
// GET 요청 객체 생성
val builder: Request.Builder = Request.Builder().url(url).get()
val request: Request = builder.build()
// Blog.LOGE("telegram before request ")
// OkHttp 클라이언트로 GET 요청 객체 전송
val response: Response = client.newCall(request).execute()
Blog.LOGE("addresses $address")
locationScope.launch {
kotlinx.coroutines.delay(5000L)
try {
val url = "https://api.weatherapi.com/v1/current.json?key=${PrefString.weatherApiKey.get()}&q=${lat},${long}&aqi=no"
if (url.length > 10) {
val request = Request.Builder().url(url).get().build()
bums.lunatic.launcher.utils.NetworkClient.client.newCall(request).execute().use { response ->
if (response.isSuccessful) {
// 응답 받아서 처리
val body: ResponseBody? = response.body
if (body != null) {
var result = body.string()
var w = Gson().fromJson<CurrentWeather>(result,CurrentWeather::class.java)
var address =addresses.first()
val result = response.body?.string()
if (result != null) {
val w = Gson().fromJson(result, CurrentWeather::class.java)
w.addr = address.getAddressLine(0)
lastWeather.clear()
lastWeather.addAll(w.getSummaryInfo())
// Blog.LOGE("Location >>> ${result}\n${lastWeather}")
synchronized(lastWeather) {
lastWeather.clear()
lastWeather.addAll(w.getSummaryInfo())
}
}
} else Blog.LOGE("telegram Error Occurred")
} else {
Blog.LOGE("weatherapi Error Occurred: ${response.code}")
}
}
} catch (e: java.lang.Exception) {
e.printStackTrace()
}
}, 5, TimeUnit.SECONDS)
// }
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
// addresses.forEach { }
}
}
} catch (e: IOException) {
} catch (e: Exception) {
e.printStackTrace()
}
}