0

I am working on Thread Queue. My aim is ensure not overlap that more than one toast at same time. Example Call toasts in onCreate,onStart,onResume states.

Firsty i create a class for toast helper that has toast queue with activity context. That queue execute a thread until queue has no items but this code is not work. But i dont know toast how to do wait a thread for toast ? if i use Thread.Sleep(4000) then main UI freezes

 public static void CreateToast(final ToastSettings toastSettings) {
        _toastQueue.add(toastSettings);
        if (_toastQueue.size() == 1) {
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    while (_toastQueue.size() != 0) {
                        Toast.makeText(_toastQueue.get(0).getContext(), _toastQueue.get(0).getMessage(), _toastQueue.get(0).isLong() ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT).show();
                        _toastQueue.remove(_toastQueue.get(0));
                        //thread sleep 4sec ??
                    }
                }
            });
        }
    }
OMANSAK
  • 1,066
  • 1
  • 12
  • 30

2 Answers2

0

You could use postDelayed.

Causes the Runnable r to be added to the message queue, to be run after the specified amount of time elapses.

for example:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
    //Do something after 1500ms
  }
}, 1500);
navylover
  • 12,383
  • 5
  • 28
  • 41
0

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

See this answer for why it is behaving that way.

From my understanding if you don't want it to interrupt the main thread you will need to create the Handler in a seperate thread as the handler posts the runnable on the thread it was created on.

new Thread(()->{
    _toastQueue.add(toastSettings);
    if (_toastQueue.size() == 1) {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                while (_toastQueue.size() != 0) {
                    Toast.makeText(_toastQueue.get(0).getContext(), _toastQueue.get(0).getMessage(), _toastQueue.get(0).isLong() ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT).show();
                    _toastQueue.remove(_toastQueue.get(0));
                    //thread sleep 4sec ??
                }
            }
        });
    }
}).start();

Wrapping the code you have in a separate thread and starting it should allow the toast to run independently from the main.

billy.mccarthy
  • 122
  • 1
  • 11