Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

710
Vistas
¿Qué uso ahora que Handler() está en desuso?

¿Cómo soluciono la advertencia de obsolescencia en este código? Alternativamente, ¿hay alguna otra opción para hacer esto?

 Handler().postDelayed({ context?.let { //code } }, 3000)
over 4 years ago · Santiago Trujillo
19 Respuestas
Responde la pregunta

0

Use Executor en lugar de handler para obtener más información Executor .
Para lograr el retraso posterior, use ScheduledExecutorService :

 ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor(); Runnable runnable = () -> { public void run() { // Do something } }; worker.schedule(runnable, 2000, TimeUnit.MILLISECONDS);
over 4 years ago · Santiago Trujillo Denunciar

0

Considere el uso de rutinas

 scope.launch { delay(3000L) // do stuff }
over 4 years ago · Santiago Trujillo Denunciar

0

La función en desuso es ese constructor para Handler. Use Handler(Looper.myLooper()) .postDelayed(runnable, delay) en su lugar

over 4 years ago · Santiago Trujillo Denunciar

0

Según el documento ( https://developer.android.com/reference/android/os/Handler#Handler() ):

La elección implícita de un Looper durante la construcción del controlador puede provocar errores en los que las operaciones se pierden silenciosamente (si el controlador no espera nuevas tareas y se cierra), bloqueos (si a veces se crea un controlador en un subproceso sin un Looper activo) o condiciones de carrera, donde el subproceso con el que está asociado un controlador no es lo que anticipó el autor. En su lugar, usa un Ejecutor o especifica el Looper explícitamente, usando Looper#getMainLooper, {link android.view.View#getHandler}, o similar. Si se requiere el comportamiento local del subproceso implícito para la compatibilidad, use el nuevo controlador (Looper.myLooper()) para dejarlo claro a los lectores.

Deberíamos dejar de usar el constructor sin un Looper y especificar un Looper en su lugar.

over 4 years ago · Santiago Trujillo Denunciar

0

Proporcione un looper en el constructor de controladores

 Handler(Looper.getMainLooper())
over 4 years ago · Santiago Trujillo Denunciar

0

Usar el alcance del ciclo de vida es más fácil. Actividad interior o fragmento.

 lifecycleScope.launch { delay(2000) // Do your stuff }

o usar el controlador

 Handler(Looper.myLooper()!!)
over 4 years ago · Santiago Trujillo Denunciar

0

utilizar esta

 Looper.myLooper()?.let { Handler(it).postDelayed({ //Your Code },2500) }
over 4 years ago · Santiago Trujillo Denunciar

0

El código handler() etc. lo genera Android Studio 4.0.1 cuando, por ejemplo, se crea desde cero una actividad de pantalla completa. Sé que se nos anima a usar Kotlin, lo cual hago, pero de vez en cuando uso proyectos de muestra para tener una idea. Parece extraño que AS nos castigue cuando AS en realidad genera el código. Podría ser una actividad académica útil revisar los errores y corregirlos, pero tal vez AS podría generar un nuevo código limpio para nosotros, los entusiastas...

over 4 years ago · Santiago Trujillo Denunciar

0

Si está utilizando Variable para Handler y Runnable, utilícelo así.

 private Handler handler; private Runnable runnable; handler = new Handler(Looper.getMainLooper()); handler.postDelayed(runnable = () -> { // Do delayed stuff here handler.postDelayed(runnable, 1000); }, delay);

También debe eliminar las devoluciones de llamada en onDestroy ()

 @Override public void onDestroy() { super.onDestroy(); if (handler != null) { handler.removeCallbacks(runnable); } }
over 4 years ago · Santiago Trujillo Denunciar

0

Yo suelo usar este

Código:

 Handler(Looper.myLooper() ?: return).postDelayed({ // Code what do you want }, 3000)

Captura de pantalla:

ingrese la descripción de la imagen aquí

over 4 years ago · Santiago Trujillo Denunciar

0

Es buena idea usar esta estructura en Kotlin

 companion object Run { fun after(delay: Long, process: () -> Unit) { Handler(Looper.getMainLooper()).postDelayed({ process() }, delay) } }

Más tarde llamar como

 Run.after(SPLASH_TIME_OUT) { val action = SplashFragmentDirections.actionSplashFragmentToLogin() v.findNavController().navigate(action) }
over 4 years ago · Santiago Trujillo Denunciar

0

Respuesta Java

Escribí un método para usar fácilmente. Puede utilizar este método directamente en su proyecto. delayTimeMillis puede ser 2000, lo que significa que este código se ejecutará después de 2 segundos.

 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); }
over 4 years ago · Santiago Trujillo Denunciar

0

Si desea evitar el control nulo en Kotlin ( ? o !! ), puede usar Looper.getMainLooper() si su Handler está trabajando con algo relacionado con la interfaz de usuario, como este:

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

Nota: use requireContext() en lugar de this@MainActivity si está usando fragment.

over 4 years ago · Santiago Trujillo Denunciar

0

Solo el constructor sin parámetros está en desuso, ahora se prefiere que especifique el Looper en el constructor a través del método Looper.getMainLooper() .

Úsalo para Java

 new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { // Your Code } }, 3000);

Úsalo para Kotlin

 Handler(Looper.getMainLooper()).postDelayed({ // Your Code }, 3000)
over 4 years ago · Santiago Trujillo Denunciar

0

A partir del nivel de API 30, hay 2 constructores obsoletos.

  • Manipulador()

  • Manejador(Manejador.Devolución de llamada)

Google explica el motivo a continuación.

La elección implícita de un Looper durante la construcción del controlador puede provocar errores en los que las operaciones se pierden silenciosamente (si el controlador no espera nuevas tareas y se cierra), bloqueos (si a veces se crea un controlador en un subproceso sin un Looper activo) o condiciones de carrera, donde el subproceso con el que está asociado un controlador no es lo que anticipó el autor. En su lugar, usa un Ejecutor o especifica el Looper explícitamente, usando Looper#getMainLooper, {link android.view.View#getHandler}, o similar. Si se requiere el comportamiento local del subproceso implícito para la compatibilidad, use el nuevo controlador (Looper.myLooper(), devolución de llamada) para dejarlo claro a los lectores.

Solución 1: use un ejecutor

1. Ejecutar código en el hilo principal.

Java

 // Create an executor that executes tasks in the main thread. Executor mainExecutor = ContextCompat.getMainExecutor(this); // Execute a task in the main thread mainExecutor.execute(new Runnable() { @Override public void run() { // You code logic goes here. } });

kotlin

 // Create an executor that executes tasks in the main thread. val mainExecutor = ContextCompat.getMainExecutor(this) // Execute a task in the main thread mainExecutor.execute { // You code logic goes here. }

2. Ejecutar código en un subproceso en segundo plano

Java

 // Create an executor that executes tasks in a background thread. ScheduledExecutorService backgroundExecutor = Executors.newSingleThreadScheduledExecutor(); // Execute a task in the background thread. backgroundExecutor.execute(new Runnable() { @Override public void run() { // Your code logic goes here. } }); // Execute a task in the background thread after 3 seconds. backgroundExecutor.schedule(new Runnable() { @Override public void run() { // Your code logic goes here } }, 3, TimeUnit.SECONDS);

kotlin

 // Create an executor that executes tasks in a background thread. val backgroundExecutor: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor() // Execute a task in the background thread. backgroundExecutor.execute { // Your code logic goes here. } // Execute a task in the background thread after 3 seconds. backgroundExecutor.schedule({ // Your code logic goes here }, 3, TimeUnit.SECONDS)

Nota: Recuerde apagar el ejecutor después de usarlo.

 backgroundExecutor.shutdown(); // or backgroundExecutor.shutdownNow();

3. Ejecute el código en un subproceso en segundo plano y actualice la interfaz de usuario en el subproceso principal.

Java

 // Create an executor that executes tasks in the main thread. Executor mainExecutor = ContextCompat.getMainExecutor(this); // Create an executor that executes tasks in a background thread. ScheduledExecutorService backgroundExecutor = Executors.newSingleThreadScheduledExecutor(); // Execute a task in the background thread. backgroundExecutor.execute(new Runnable() { @Override public void run() { // Your code logic goes here. // Update UI on the main thread mainExecutor.execute(new Runnable() { @Override public void run() { // You code logic goes here. } }); } });

kotlin

 // Create an executor that executes tasks in the main thread. val mainExecutor: Executor = ContextCompat.getMainExecutor(this) // Create an executor that executes tasks in a background thread. val backgroundExecutor = Executors.newSingleThreadScheduledExecutor() // Execute a task in the background thread. backgroundExecutor.execute { // Your code logic goes here. // Update UI on the main thread mainExecutor.execute { // You code logic goes here. } }

Solución 2: Especifique un Looper explícitamente usando uno de los siguientes constructores.

  • Manejador (Looper)

  • Controlador (Looper, Controlador. Devolución de llamada)

1. Ejecutar código en el hilo principal

1.1. Manejador con Looper

Java

 Handler mainHandler = new Handler(Looper.getMainLooper());

kotlin

 val mainHandler = Handler(Looper.getMainLooper())

1.2 Manejador con un Looper y un Manejador. Devolución de llamada

Java

 Handler mainHandler = new Handler(Looper.getMainLooper(), new Handler.Callback() { @Override public boolean handleMessage(@NonNull Message message) { // Your code logic goes here. return true; } });

kotlin

 val mainHandler = Handler(Looper.getMainLooper(), Handler.Callback { // Your code logic goes here. true })

2. Ejecutar código en un subproceso en segundo plano

2.1. Manejador con Looper

Java

 // Create a background thread that has a Looper HandlerThread handlerThread = new HandlerThread("HandlerThread"); handlerThread.start(); // Create a handler to execute tasks in the background thread. Handler backgroundHandler = new Handler(handlerThread.getLooper());

kotlin

 // Create a background thread that has a Looper val handlerThread = HandlerThread("HandlerThread") handlerThread.start() // Create a handler to execute tasks in the background thread. val backgroundHandler = Handler(handlerThread.looper)

2.2. Manejador con un Looper y un Manejador. Devolución de llamada

Java

 // Create a background thread that has a Looper HandlerThread handlerThread = new HandlerThread("HandlerThread"); handlerThread.start(); // Create a handler to execute taks in the background thread. Handler backgroundHandler = new Handler(handlerThread.getLooper(), new Handler.Callback() { @Override public boolean handleMessage(@NonNull Message message) { // Your code logic goes here. return true; } });

kotlin

 // Create a background thread that has a Looper val handlerThread = HandlerThread("HandlerThread") handlerThread.start() // Create a handler to execute taks in the background thread. val backgroundHandler = Handler(handlerThread.looper, Handler.Callback { // Your code logic goes here. true })

Nota: Recuerde soltar el hilo después de usar.

 handlerThread.quit(); // or handlerThread.quitSafely();

3. Ejecute el código en un subproceso en segundo plano y actualice la interfaz de usuario en el subproceso principal.

Java

 // Create a handler to execute code in the main thread Handler mainHandler = new Handler(Looper.getMainLooper()); // Create a background thread that has a Looper HandlerThread handlerThread = new HandlerThread("HandlerThread"); handlerThread.start(); // Create a handler to execute in the background thread Handler backgroundHandler = new Handler(handlerThread.getLooper(), new Handler.Callback() { @Override public boolean handleMessage(@NonNull Message message) { // Your code logic goes here. // Update UI on the main thread. mainHandler.post(new Runnable() { @Override public void run() { } }); return true; } });

kotlin

 // Create a handler to execute code in the main thread val mainHandler = Handler(Looper.getMainLooper()) // Create a background thread that has a Looper val handlerThread = HandlerThread("HandlerThread") handlerThread.start() // Create a handler to execute in the background thread val backgroundHandler = Handler(handlerThread.looper, Handler.Callback { // Your code logic goes here. // Update UI on the main thread. mainHandler.post { } true })
over 4 years ago · Santiago Trujillo Denunciar

0

Corrutinas Kotlin

 private val SPLASH_SCREEN_TIME_OUT_CONST: Long = 3000 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash) window.setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN ) GlobalScope.launch { delay(SPLASH_SCREEN_TIME_OUT_CONST) goToIntro() } } private fun goToIntro(){ startActivity(Intent(this, IntroActivity::class.java)) finish() }
over 4 years ago · Santiago Trujillo Denunciar

0

Los constructores Handler() y Handler(Handler.Callback callback) están en desuso. Porque eso puede conducir a errores y fallas. Usa Executor o Looper explícitamente.

para Java

 Handler handler = new Handler(Looper.getMainLooper()); handler.postDelayed(new Runnable() { @Override public void run() { //do your work here } }, 1000);
over 4 years ago · Santiago Trujillo Denunciar

0

import android.os.Looper import android.os.Handler inline fun delay(delay: Long, crossinline completion: () -> Unit) { Handler(Looper.getMainLooper()).postDelayed({ completion() }, delay) }

Ejemplo:

 delay(1000) { view.refreshButton.visibility = View.GONE }
over 4 years ago · Santiago Trujillo Denunciar

0

Tengo 3 soluciones :

  1. Especifique el Looper explícitamente:
     Handler(Looper.getMainLooper()).postDelay({ // code })
  2. Especifique el comportamiento local del subproceso implícito:
     Handler(Looper.myLooper()!!).postDelay({ // code })
  3. usando Thread :
     Thread({ try{ Thread.sleep(3000) } catch (e : Exception) { throw e } // code }).start() `
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda