03/11/2018, 11:56

Burrito Thread in Android - understand thread in a fun way

Let's imagine Thread is a burrito truck Runnable would be the recipe how to make a burrito Message which is sent to Handler is like a order from customer "A breakfast burrito, please !" Runnable + Message = Order Handler would be Tim who makes burrito Message Queue would ...

Let's imagine

Thread is a burrito truck Runnable would be the recipe how to make a burrito
Message which is sent to Handler is like a order from customer "A breakfast burrito, please !"
Runnable + Message = Order
Handler would be Tim who makes burrito
Message Queue would be the list of orders is taken by Tim and he put it at the end of the list
Looper is Tim's daughter who really want to help her dad, but she is too young, so when she notices her dad is about to finish an order, then she grabs the order and give it to her dad.

final DownloadThread thread = new DownloadThread();
thread.setName("DownloadThread");
thread.start();

mDownloadButton = findViewById(R.id.mDownloadButton);
mDownloadButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast.makeText(MainActivity.this, "Downloading", Toast.LENGTH_LONG).show();
        // Send Messages to Handler for processing
        for (String song : Playlist.songs) {
            Message message = Message.obtain();
            message.obj = song;
            thread.mHandler.sendMessage(message);
        }
    }
});
public class DownloadThread extends Thread {

    public DownloadHandler mHandler;

    @Override
    public void run() {
        Looper.prepare(); // creates a looper for a thread and also creates the message queue
        mHandler = new DownloadHandler();
        Looper.loop(); // Looping over the message queue
    }
}
public class DownloadHandler extends Handler {
    private static final String TAG = DownloadHandler.class.getSimpleName();

    @Override
    public void handleMessage(Message msg) {
        downloadSong(msg.obj.toString());
    }

    private void downloadSong(String song) {
        long endTime = System.currentTimeMillis() + 10 * 1000;
        while (System.currentTimeMillis() < endTime) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        Log.d(TAG, song + " Song downloaded");
    }
}

So who is the Services ???             </div>
            
            <div class=

0