Junior — Middle
Kuidas rakendada Androidis eraldi niiti sõnumite töötlemiseks, kasutades HandlerThread-i?
sobes.tech AI
Vastus AI-lt
To create a separate thread for message processing in Android, you can use the HandlerThread class. It creates a thread with its own Looper, which allows processing of the message queue.
Usage example:
HandlerThread handlerThread = new HandlerThread("MyHandlerThread");
handlerThread.start();
// Create a Handler associated with this thread's Looper
Handler handler = new Handler(handlerThread.getLooper()) {
@Override
public void handleMessage(Message msg) {
// Process message in a separate thread
}
};
// Send a message to the queue
Message msg = handler.obtainMessage();
handler.sendMessage(msg);
This way, all messages sent to this Handler will be processed in a separate thread, without blocking the main UI thread.