Was verwende ich jetzt, da Handler() veraltet ist?

Lesezeit: 6 Minuten

Was verwende ich jetzt da Handler veraltet ist
Hari ShankarS

Wie behebe ich die Verfallswarnung in diesem Code? Gibt es alternativ dazu noch andere Möglichkeiten?

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

1643437626 469 Was verwende ich jetzt da Handler veraltet ist
Nikunj Paradva

Nur der parameterlose Konstruktor ist veraltet, es wird jetzt bevorzugt, dass Sie den angeben Looper im Konstruktor über die Looper.getMainLooper() Methode.

Verwenden Sie es für Java

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

Verwenden Sie es für Kotlin

Handler(Looper.getMainLooper()).postDelayed({
    // Your Code
}, 3000)

  • Geradeaus …

    – Fahmi Eshaq

    3. Januar um 9:54

Was verwende ich jetzt da Handler veraltet ist
Nikolaus Jafelle

Wenn Sie die Nullprüfung in Kotlin vermeiden möchten (? oder !!) können Sie verwenden Looper.getMainLooper() wenn dein Handler arbeitet mit einer UI-bezogenen Sache, wie dieser:

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

Hinweis: verwenden requireContext() anstatt this@MainActivity wenn Sie fragment verwenden.

Ab API-Level 30 sind 2 Konstruktoren veraltet.

Google erklärt den Grund unten.

Die implizite Auswahl eines Loopers während der Handler-Erstellung kann zu Fehlern führen, bei denen Operationen stillschweigend verloren gehen (wenn der Handler keine neuen Aufgaben erwartet und beendet wird), Abstürze (wenn ein Handler manchmal in einem Thread ohne aktiven Looper erstellt wird) oder Race-Bedingungen. wo der Thread, dem ein Handler zugeordnet ist, nicht das ist, was der Autor erwartet hat. Verwenden Sie stattdessen einen Executor oder geben Sie den Looper explizit an, indem Sie Looper#getMainLooper, {link android.view.View#getHandler} oder ähnliches verwenden. Wenn das lokale Verhalten des impliziten Threads aus Kompatibilitätsgründen erforderlich ist, verwenden Sie new Handler(Looper.myLooper(), callback), um es den Lesern klar zu machen.

Lösung 1: Benutze ein Testamentsvollstrecker

1. Code im Hauptthread ausführen.

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. Code in einem Hintergrundthread ausführen

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)

Notiz: Denken Sie daran, den Executor nach der Verwendung herunterzufahren.

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

3. Führen Sie Code in einem Hintergrundthread aus und aktualisieren Sie die Benutzeroberfläche im Hauptthread.

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.
    }
}

Lösung 2: Geben Sie einen Looper explizit an, indem Sie einen der folgenden Konstruktoren verwenden.

1. Code im Hauptthread ausführen

1.1. Handler mit einem Looper

Java

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

Kotlin

val mainHandler = Handler(Looper.getMainLooper())

1.2 Handler mit einem Looper und einem Handler.Callback

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. Code in einem Hintergrundthread ausführen

2.1. Handler mit einem 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. Handler mit einem Looper und einem Handler.Callback

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
})

Notiz: Denken Sie daran, den Faden nach der Verwendung zu lösen.

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

3. Führen Sie Code in einem Hintergrundthread aus und aktualisieren Sie die Benutzeroberfläche im Hauptthread.

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
})

  • tolles Zeug ! Beifall

    – madhu527

    23. Januar 21 um 6:49 Uhr

Die veraltete Funktion ist dieser Konstruktor für Handler. Benutzen Handler(Looper.myLooper()) .postDelayed(runnable, delay) stattdessen

Erwägen Sie die Verwendung von Coroutinen

scope.launch {
    delay(3000L)
    // do stuff
}

  • Innen Activity oder Fragment: lifecycleScope.launch { delay(3000L) }

    – Mahmudul Hasan Shohag

    7. Oktober 20 um 13:18 Uhr

Mit dem Lebenszyklusumfang ist dies einfacher. Innere Aktivität oder Fragment.

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

oder Handler verwenden

        Handler(Looper.myLooper()!!)

  • Innen Activity oder Fragment: lifecycleScope.launch { delay(3000L) }

    – Mahmudul Hasan Shohag

    7. Oktober 20 um 13:18 Uhr

1643437627 615 Was verwende ich jetzt da Handler veraltet ist
dStulle

benutze das

Looper.myLooper()?.let {
    Handler(it).postDelayed({
        //Your Code
    },2500)
}

.

684540cookie-checkWas verwende ich jetzt, da Handler() veraltet ist?

This website is using cookies to improve the user-friendliness. You agree by using the website further.

Privacy policy