티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How to call a method after a delay in Android
안드로이드에서 딜레이 후 메소드 호출하는 방법
문제 내용
I want to be able to call the following method after a specified delay. In objective c there was something like:
지정된 시간 후에 다음 메소드를 호출할 수 있도록 하려고 합니다. Objective C에서는 다음과 같은 것이 있었습니다.
[self performSelector:@selector(DoSomething) withObject:nil afterDelay:5];
Is there an equivalent of this method in android with java? For example I need to be able to call a method after 5 seconds.
Java에서 Android에서 이 메서드와 유사한 메서드가 있나요? 예를 들어, 5 초 후에 메서드를 호출 할 수 있어야합니다.
public void DoSomething()
{
//do something here
}
높은 점수를 받은 Solution
Kotlin
Handler(Looper.getMainLooper()).postDelayed({
//Do something after 100ms
}, 100)
Java
final Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);
The class to import is android.os.handler
.
가져와야 하는 클래스는 android.os.handler 입니다.
가장 최근 달린 Solution
More Safety - With Kotlin Coroutine
Kotlin 코루틴을 사용하면 더욱 안전합니다.
Most of the answers use Handler but I give a different solution to delay in activity, fragment, view model with Android Lifecycle ext. This way will auto cancel when the lifecycle begins destroyed - avoid leaking the memory or crashed app
대부분의 답변은 Handler를 사용하지만, 저는 Android Lifecycle ext로 액티비티, 프래그먼트, 뷰 모델에서 지연을 구현하는 다른 방법을 제시합니다. 이 방법은 라이프사이클이 종료되면 자동으로 취소되므로 메모리 누수나 앱 충돌을 방지할 수 있습니다.
In Activity or Fragment:
액티비티나 프래그먼트에서:
lifecycleScope.launch {
delay(DELAY_MS)
doSomething()
}
In ViewModel:
ViewModel에서:
viewModelScope.lanch {
delay(DELAY_MS)
doSomething()
}
In suspend function: (Kotlin Coroutine)
중단 가능한 함수 내에서: (Kotlin Coroutine)
suspend fun doSomethingAfter(){
delay(DELAY_MS)
doSomething()
}
If you get an error with the lifecycleScope not found! - import this dependency to the app gradle file:
중단 가능한 함수 내에서: (Kotlin Coroutine)
implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.4.0"
출처 : https://stackoverflow.com/questions/3072173/how-to-call-a-method-after-a-delay-in-android
'개발 > 안드로이드' 카테고리의 다른 글
ScrollView의 끝 감지하기 (0) | 2023.03.08 |
---|---|
ContentProvider 없이 CursorLoader 사용 방법 (0) | 2023.03.07 |
Android를 사용하여 HTTP 요청 만들기 (0) | 2023.03.07 |
LocalBroadcastManager를 사용하는 방법 (0) | 2023.03.06 |
"java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema" 오류 수정하기 (0) | 2023.03.06 |