When we try to execute long running operations on the app’s main thread (also called the UI thread), we freeze the app’s user interface and after a couple seconds we get an “application not responding” dialog message with the option to force quit the app. To avoid this we have to move heavy operations like database manipulation and network requests onto a separate thread.
In this video we will learn how to create such a separate worker thread in Android. For this we can either create a class that extends Thread and override it’s run method, or create a class that implements the Runnable interface, and then pass this Runnable to a new Thread object.
These core Java classes build the foundation for classes like AsyncTask, HandlerThread and ThreadPoolExecutor.
We will also learn how to send code from the background thread back to the UI thread by calling post on a Handler that sends a runnable to the MessageQueue of the UI thread. To associate the Handler with the Looper of the main thread, we either instantiate it on the main thread, or pass Looper.getMainLooper to the constructor.
Instead of creating a handler, we can also use the View classes post method or the Activity classes runOnUiThread method, that use the main handler internally.

Great explainer video by the Android developer team about threads, handlers, loopers etc:

Watch this playlist to learn more about Looper, MessageQueue & Handler:

Example code:

____________________
❗ Subscribe to the channel:

⏯ Watch more tutorials:

㊙ Help translating the videos:

💚 Support the content:

💬 Join the Discord chat:

🎧 Audiobooks and podcasts for programmers:

👶 How to get started with Android development:

📣 Follow Coding in Flow on social media:

Facebook:

Instagram:

Twitter:

Blog:

Nguồn:https://u-os.org/

Xem Thêm Bài Viết Khác:https://u-os.org/cong-nghe

Author

47 Comments

  1. Ahmad Zaki Sokhaimi Reply

    All the weird and confusing stuff I've been reading about this topic for the past few days, which I can't seem to wrap my head around, suddenly they all make sense after watching your video. Keep up the good work, sir!

  2. Samora Mabuya Reply

    You are very good at explaining complex tasks. Thank you.

  3. Thank you Sir, it is very very good explanation.

    At 7:51 no app crash in my code without using Handler.
    but why?

  4. Thank you very much Sir for this informative tutorial….you explained it well and with all details…..I was trying to read data from bluetooth module which sends data from arduino to android app and your tutorial helped me creating a thread which does it in background and update textview. appreciated. Looking forward for more from you…subscribed… Thanks for your time and effort and spreading knowledge.

  5. NERYA SHEETRIT Reply

    Great video!!! Can I run the thread multiple times? E.G every time a location changes, I want to run the thread

  6. Pooja Patel Reply

    I'm a teacher of Computer Science and teach android programming. Thanks to you i have learnt android so well. You explain each and every concept very clearly and your examples are very good. Thank you so much. God bless you!!!

  7. carl evan virtucio Reply

    love the vid.. but the app that i make keeps crashing.. may be you can help me why…. plsssss

  8. saleem kalro Reply

    Great Teacher, Great Method of teaching, Great Collection of content. Thanks

  9. bazzingalore Reply

    Damn I wish I had seen this before my interview yesterday.

  10. Anil Philip Reply

    these are the best android videos I have seen. I am guessing you work at google? 😉

  11. I noticed something really interesting. At 7:51, the button text changes from "Start" to "50%" and THEN crashes. Then we are shown that there is an exception. What this apparently means is that Android CAN touch its views, but will throw an exception, and not crash, when it does. Also, thanks for ALL of the great videos you do.

  12. Osama Ghazal Reply

    You are great man, Done Successfully
    Thank you very much

  13. mladen ilisevic Reply

    Man, thank you so much. You have a great way to simply present a complex thing.

  14. Gol Duhoki Reply

    Thank you very much for this tutorial it really helps me. You are the best instructor i have ever seen. Do u have any course on udemy?

  15. Hi, in my previous interview, interviewer ask about threadpool concept and use method. I stick to your tutorial in youtube for android learning. Maybe it is glad to consider making a tutorial about threadpool in Android

  16. Puthea Mam Reply

    you said, "Only the original thread that created a view hierarchy can touch its views".
    And yes, I can't change the text of my textview from another thread. However, I can change the progress value of my progress bar from another thread. Can you explain why? it's shock
    Thank you for this great tutorial ❤

  17. Javad Ahamad Reply

    Thanks again. when I put my code to the run method the ui is not responding. I have to copy all the firebase database values to sqlite database as background thread(normally last for 5 to 6 sec). the code is working but my custom keyboard is not responding until the code execute. but when I tried your example, the keyboard is alive.  please help me.

    class ExampleThread extends Thread
    {
    @Override
    public void run() {

    ChildCounter=0;

    DatabaseReference Ref = FirebaseDatabase.getInstance().getReference("English");
    Ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

    datasnapshotChildren=dataSnapshot.getChildrenCount();

    for (DataSnapshot PostSnapShot : dataSnapshot.getChildren()) {
    String englishWord = PostSnapShot.child("english").getValue().toString();
    String correspondingWord = PostSnapShot.child("correspondingWord").getValue().toString();
    ChildCounter++;

    Log.e("Service","xyz : Copying.. "+ChildCounter+"/"+datasnapshotChildren+" "+ correspondingWord);
    boolean insertData1 = databaseHelper.save_to_list(englishWord, correspondingWord, 1);

    }

    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
    });

    }
    }

    please give a solution

  18. Raghul Siddarth Reply

    Really great content. Do you have any plans of doing videos on view hierarchy. Like how draw, layout and measure are called and used by the system?

  19. Nicolas Helios Reply

    You are an very good teacher!
    Probably one of the best I have seen.
    Are you German speaking?
    I hear a slight German accent.

    I recently started with Android Studio.
    The threading in Java is a bit complicated, but thanks to your video,
    I look much better, thanks a lot !!! :)))))

    Greetings from Switzerland
    Nicolas B)

  20. Sagar Ghare Reply

    YOOOOO. Understood thread after learning android since 2 years. heheh. enjoyed ..thanks a lot.

  21. R Banerjee Reply

    I study computer science at university and I have to say, your videos are the clearest, best-explained coding videos I've seen on YouTube! Thank you so much for doing what you do!

  22. Miklós Hevér Reply

    Well designed, clearly presented educational video. Congratulations.

  23. There is no person who teach like this except Coding in Flow… lol

  24. Benedict Contawe Reply

    can you create service and intentservice tutorials

  25. Afif Shaikh Reply

    how buttons are working without giving onclick to them?

  26. Banja DENIS VICTOR Reply

    Thanks alot in have been threading in a complicated way

  27. Delowar Hossain Reply

    if i close the app will background task still work?

Write A Comment