How do you display a Toast from a background thread on Android?

后端 未结 11 2023
难免孤独
难免孤独 2020-11-22 05:03

How can I display Toast messages from a thread?

11条回答
  •  轮回少年
    2020-11-22 05:39

    Sometimes, you have to send message from another Thread to UI thread. This type of scenario occurs when you can't execute Network/IO operations on UI thread.

    Below example handles that scenario.

    1. You have UI Thread
    2. You have to start IO operation and hence you can't run Runnable on UI thread. So post your Runnable to handler on HandlerThread
    3. Get the result from Runnable and send it back to UI thread and show a Toast message.

    Solution:

    1. Create a HandlerThread and start it
    2. Create a Handler with Looper from HandlerThread:requestHandler
    3. Create a Handler with Looper from Main Thread: responseHandler and override handleMessage method
    4. post a Runnable task on requestHandler
    5. Inside Runnable task, call sendMessage on responseHandler
    6. This sendMessage result invocation of handleMessage in responseHandler.
    7. Get attributes from the Message and process it, update UI

    Sample code:

        /* Handler thread */
    
        HandlerThread handlerThread = new HandlerThread("HandlerThread");
        handlerThread.start();
        Handler requestHandler = new Handler(handlerThread.getLooper());
    
        final Handler responseHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
                //txtView.setText((String) msg.obj);
                Toast.makeText(MainActivity.this,
                        "Runnable on HandlerThread is completed and got result:"+(String)msg.obj,
                        Toast.LENGTH_LONG)
                        .show();
            }
        };
    
        for ( int i=0; i<5; i++) {
            Runnable myRunnable = new Runnable() {
                @Override
                public void run() {
                    try {
    
                        /* Add your business logic here and construct the 
                           Messgae which should be handled in UI thread. For 
                           example sake, just sending a simple Text here*/
    
                        String text = "" + (++rId);
                        Message msg = new Message();
    
                        msg.obj = text.toString();
                        responseHandler.sendMessage(msg);
                        System.out.println(text.toString());
    
                    } catch (Exception err) {
                        err.printStackTrace();
                    }
                }
            };
            requestHandler.post(myRunnable);
        }
    

    Useful articles:

    handlerthreads-and-why-you-should-be-using-them-in-your-android-apps

    android-looper-handler-handlerthread-i

提交回复
热议问题