写点什么

如何在子线程中使用 Toast 显示消息

用户头像
Geek_416be1
关注
发布于: 2021 年 03 月 13 日
  new Thread(new Runnable() {            @Override            public void run() {                Looper.prepare();                Toast.makeText(MainActivity.this,"haha", Toast.LENGTH_LONG).show();                Looper.loop();            }        }).start();  
复制代码


 new Thread(new Runnable() {            @Override            public void run() {               runOnUiThread(new Runnable() {                   @Override                   public void run() {                        Toast.makeText(MainActivity.this,"haha", Toast.LENGTH_LONG).show();                   }               });            }        }).start();
复制代码


另外,使用 Handler+Thread


Class used to run a message loop for a thread. Threads by default do

* not have a message loop associated with them; to create one, call

* {@link #prepare} in the thread that is to run the loop, and then

* {@link #loop} to have it process messages until the loop is stopped.

*

* <p>Most interaction with a message loop is through the

* {@link Handler} class.

*

* <p>This is a typical example of the implementation of a Looper thread,

* using the separation of {@link #prepare} and {@link #loop} to create an

* initial Handler to communicate with the Looper.

*

* <pre>

* class LooperThread extends Thread {

* public Handler mHandler;

*

* public void run() {

* Looper.prepare();

*

* mHandler = new Handler() {

* public void handleMessage(Message msg) {

* // process incoming messages here

* }

* };

*

* Looper.loop();

* }

* }</pre>

*/


/** Initialize the current thread as a looper.

* This gives you a chance to create handlers that then reference

* this looper, before actually starting the loop. Be sure to call

* {@link #loop()} after calling this method, and end it by calling

* {@link #quit()}.

*/

public static void prepare() {

prepare(true);

}


/**

* Run the message queue in this thread. Be sure to call

* {@link #quit()} to end the loop.

*/

public static void loop() {


}


用户头像

Geek_416be1

关注

还未添加个人签名 2020.08.27 加入

还未添加个人简介

评论

发布
暂无评论
如何在子线程中使用Toast显示消息