Android App Development for Beginners – 39 – Threads

[ad_1]
Facebook –
GitHub –
Google+ –
LinkedIn –
reddit –
Support –
thenewboston –
Twitter –


Posted

in

by

Tags:

Comments

37 responses to “Android App Development for Beginners – 39 – Threads”

  1. Righty SnipeZ Avatar

    9:18 Guys Lauren isn't responding what do we do?
    "OK"
    Shit we killed Lauren.

  2. kelvin torver Avatar

    hello sir…. how can i write a program to execute three different tasks at different intervals preceded from one another using thread and handler or any method in android studio???….lets assume task 1 starts at time t1=30secs, task 2 at t2=50sec and task three t3=60secs aynchronously

  3. imran sifat Avatar

    lauren isn't responding…lauren who ur another mistake?? :V

  4. Vach Davtyan Avatar

    I can not fix sendEmptyMessage, it's written in red

  5. Vach Davtyan Avatar

    public class MainActivity extends Activity {

    final String LOG_TAG = "myLogs";

    final int STATUS_NONE = 0; // нет подключения
    final int STATUS_CONNECTING = 1; // подключаемся
    final int STATUS_CONNECTED = 2; // подключено
    final int STATUS_DOWNLOAD_START = 3; // загрузка началась
    final int STATUS_DOWNLOAD_FILE = 4; // файл загружен
    final int STATUS_DOWNLOAD_END = 5; // загрузка закончена
    final int STATUS_DOWNLOAD_NONE = 6; // нет файлов для загрузки

    Handler h;

    TextView tvStatus;
    ProgressBar pbDownload;
    Button btnConnect;

    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    tvStatus = (TextView) findViewById(R.id.tvStatus);
    pbDownload = (ProgressBar) findViewById(R.id.pbDownload);
    btnConnect = (Button) findViewById(R.id.btnConnect);

    h = new Handler() {
    @Override
    public void publish(LogRecord record) {

    }

    @Override
    public void flush() {

    }

    @Override
    public void close() throws SecurityException {

    }

    public void handleMessage(android.os.Message msg) {
    switch (msg.what) {
    case STATUS_NONE:
    btnConnect.setEnabled(true);
    tvStatus.setText("Not connected");
    pbDownload.setVisibility(View.GONE);
    break;
    case STATUS_CONNECTING:
    btnConnect.setEnabled(false);
    tvStatus.setText("Connecting");
    break;
    case STATUS_CONNECTED:
    tvStatus.setText("Connected");
    break;
    case STATUS_DOWNLOAD_START:
    tvStatus.setText("Start download " + msg.arg1 + " files");
    pbDownload.setMax(msg.arg1);
    pbDownload.setProgress(0);
    pbDownload.setVisibility(View.VISIBLE);
    break;
    case STATUS_DOWNLOAD_FILE:
    tvStatus.setText("Downloading. Left " + msg.arg2 + " files");
    pbDownload.setProgress(msg.arg1);
    saveFile((byte[]) msg.obj);
    break;
    case STATUS_DOWNLOAD_END:
    tvStatus.setText("Download complete!");
    break;
    case STATUS_DOWNLOAD_NONE:
    tvStatus.setText("No files for download");
    break;
    }
    };
    };

    h.sendEmptyMessage(STATUS_NONE);
    }

    public void onclick(View v) {

    Thread t = new Thread(new Runnable() {
    Message msg;
    byte[] file;
    Random rand = new Random();

    public void run() {
    try {
    // устанавливаем подключение
    h.sendEmptyMessage(STATUS_CONNECTING);
    TimeUnit.SECONDS.sleep(1);

    // подключение установлено
    h.sendEmptyMessage(STATUS_CONNECTED);

    // определяем кол-во файлов
    TimeUnit.SECONDS.sleep(1);
    int filesCount = rand.nextInt(5);

    if (filesCount == 0) {
    // сообщаем, что файлов для загрузки нет
    h.sendEmptyMessage(STATUS_DOWNLOAD_NONE);
    // и отключаемся
    TimeUnit.MILLISECONDS.sleep(1500);
    h.sendEmptyMessage(STATUS_NONE);
    return;
    }

    // загрузка начинается
    // создаем сообщение, с информацией о количестве файлов
    msg = h.obtainMessage(STATUS_DOWNLOAD_START, filesCount, 0);
    // отправляем
    h.sendMessage(msg);

    for (int i = 1; i <= filesCount; i++) {
    // загружается файл
    file = downloadFile();
    // создаем сообщение с информацией о порядковом номере
    // файла,
    // кол-вом оставшихся и самим файлом
    msg = h.obtainMessage(STATUS_DOWNLOAD_FILE, i,
    filesCount – i, file);
    // отправляем
    h.sendMessage(msg);
    }

    // загрузка завершена
    h.sendEmptyMessage(STATUS_DOWNLOAD_END);

    // отключаемся
    TimeUnit.MILLISECONDS.sleep(1500);
    h.sendEmptyMessage(STATUS_NONE);

    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    });
    t.start();
    }

    byte[] downloadFile() throws InterruptedException {
    TimeUnit.SECONDS.sleep(2);
    return new byte[1024];
    }

    void saveFile(byte[] file) {

    }

    }

  6. Tewcan Avatar

    Most instructors – "We'll call the button click me."
    and then there is Bucky. "Touch me, that's a little more perverted… maybe touch me baby, there we go."
    Where would we be without you?

  7. random crazy Avatar

    You keep touching Lauren and she doesn't respond. Gotta get a new girl.

  8. Alex Lushiku Avatar

    Why not use "wait(10000)" ?

  9. Meer Shah Avatar

    Why can't I just do wait(10000)?

  10. Rezoanur Rahman Avatar

    Came here to get a different lecture other than UDEMY ..turns out it's the exact same lecture..even the code is same..heh?
    But somehow it's better..xD

  11. ranjdar karim Avatar

    actualyy i think the while loop is redundant
    you can just type this and it works…
    public void clickBuckeysButton(View view){
    synchronized (this){
    try {
    wait(5000);
    } catch (Exception e) { }

    }
    }

  12. Wilto n Avatar

    this sample is rlly good mate

  13. Mario Vukašinović Avatar

    Happy New Year from the futureTime! 🙂

  14. Awei Hsue Avatar

    THANK YOU! ALL YOUR STUFF ARE AWESOME!!

  15. DemoGaming Avatar

    Nice job man. This tutorial helped me a lot! the next one too!

  16. Jeroen van der Schalie Avatar

    Somehow my app doesn't work. It stops the app. It seems there essential differences in androidstudio 1.0.2 that Bucky is using and 1.5.1 that I'm using. I am also using BlueStacks instead of the local emulator.

  17. kabala tübele Avatar

    another fun tutorial! 🙂 thx a lot

  18. Ola Dahl Avatar

    Why to use threads? Cause I don't want your life to be destroyed 😀

  19. Dorin B Avatar

    hi , what if i install the sendBroadcast on my phone , and i instal the recieveBroadcast on my father s phone…what will happen ? will the message be sent? and if yes do i need wi fi on ?…

  20. Wiliam Ferraciolli Avatar

    u better at coding then trying a brit accent

  21. Mr. Ontological Avatar

    What's the point of putting the wait method inside the whileloop? Since the wait() method will eventually shrink to 0 and the clickBuckysButton() method will terminate. Please help!

  22. Sohrab zia Avatar

    hahaha that accent 😀

  23. xxBIGBIRDxx Avatar

    Nice tutorial, are making games in this series?

  24. Andrew Hamilton Avatar

    That accent hurt my being

  25. Vladimir Putin Avatar

    This man just made my new year twice as better. Those jokes just make the programming 10 times more fun 🙂

  26. silenthacker66 Avatar

    +thenewboston  DAT British Accent  😀 awsome 

  27. silenthacker66 Avatar

    +thenewboston  if you are reading my comment like right now (1/12015 1:30AM) then Happy new year Bucky

  28. The Zigec Avatar

    Are you planning accent tutorials next?

Leave a Reply

Your email address will not be published. Required fields are marked *