How to solve Handler() deprecated?

后端 未结 12 1723
眼角桃花
眼角桃花 2020-12-05 09:00

Could anyone know, how to fix the deprecated warning or any alternate solution for this.

Handler().postDelayed({
    context?.let {
        //code
    }
}, 30         


        
相关标签:
12条回答
  • 2020-12-05 09:33

    Consider using coroutines

    scope.launch {
        delay(3000L)
        // do stuff
    }
    
    0 讨论(0)
  • 2020-12-05 09:36

    According to the document (https://developer.android.com/reference/android/os/Handler), "Implicitly choosing a Looper during Handler construction can lead to bugs where operations are silently lost (if the Handler is not expecting new tasks and quits), crashes (if a handler is sometimes created on a thread without a Looper active), or race conditions, where the thread a handler is associated with is not what the author anticipated. Instead, use an Executor or specify the Looper explicitly, using Looper#getMainLooper, {link android.view.View#getHandler}, or similar. If the implicit thread local behavior is required for compatibility, use new Handler(Looper.myLooper()) to make it clear to readers."

    we should quit using the constructor without a Looper, specific a Looper instead.

    0 讨论(0)
  • 2020-12-05 09:36

    The handler() etc code is generated by the Android Studio 4.0.1 when a Fullscreen Activity, for example, is created from scratch. I know that we are being encouraged to use Kotlin, which I do, but from time to time I use sample projects to get an idea going. It seems strange that we are chastised by AS when AS actually generates the code. It might be a useful academic activity to go through the errors and fix them but maybe AS could generate new clean code for us enthusiasts...

    0 讨论(0)
  • 2020-12-05 09:37

    Using lifecycle scope this is more easy. Inside activity or fragment.

     lifecycleScope.launch {
         delay(2000)
         // Do your stuff
     }
    
    0 讨论(0)
  • 2020-12-05 09:38

    Java Answer - 10.2020

    I wrote a method to use easily. You can use this method directly in your project. delayTimeMillis can be 2000, it means that this code will run after 2 seconds.

    private void runJobWithDelay(int delayTimeMillis){
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                //todo: you can call your method what you want.
            }
        }, delayTimeMillis);
    }
    

    @canerkaseler Happy coding!

    0 讨论(0)
  • 2020-12-05 09:42

    If you want to avoid the null check thing in Kotlin (? or !!) you can use Looper.getMainLooper() if your Handler is working with some UI related thing, like this:

    Handler(Looper.getMainLooper()).postDelayed({
       Toast.makeText(this@MainActivity, "LOOPER", Toast.LENGTH_SHORT).show()
    }, 3000)
    

    Note: use requireContext() instead of this@MainActivity if you are using fragment.

    0 讨论(0)
提交回复
热议问题