繁体   English   中英

如何在 Android 上显示来自后台线程的 Toast?

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

如何显示来自线程的Toast消息?

您可以通过从您的线程调用ActivityrunOnUiThread方法来实现:

activity.runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(activity, "Hello", Toast.LENGTH_SHORT).show();
    }
});

我喜欢在我的活动中有一个名为showToast的方法,我可以从任何地方调用它...

public void showToast(final String toast)
{
    runOnUiThread(() -> Toast.makeText(MyActivity.this, toast, Toast.LENGTH_SHORT).show());
}

然后,我最常从MyActivity在任何像这样的线程上调用它......

showToast(getString(R.string.MyMessage));

这与其他答案类似,但是针对新的可用 API 进行了更新,并且更加清晰。 此外,不假设您处于活动上下文中。

public class MyService extends AnyContextSubclass {

    public void postToastMessage(final String message) {
        Handler handler = new Handler(Looper.getMainLooper());

        handler.post(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(getContext(), message, Toast.LENGTH_LONG).show();
            }
        });
    }
}

一种几乎适用于任何地方(包括没有ActivityView )的方法是将Handler抓取到主线程并显示 Toast:

public void toast(final Context context, final String text) {
  Handler handler = new Handler(Looper.getMainLooper());
  handler.post(new Runnable() {
    public void run() {
      Toast.makeText(context, text, Toast.LENGTH_LONG).show();
    }
  });
}

这种方法的优点是它适用于任何Context ,包括ServiceApplication

这样这样,带有一个显示ToastRunnable 即,

Activity activity = // reference to an Activity
// or
View view = // reference to a View

activity.runOnUiThread(new Runnable() {
    @Override
    public void run() {
        showToast(activity);
    }
});
// or
view.post(new Runnable() {
    @Override
    public void run() {
        showToast(view.getContext());
    }
});

private void showToast(Context ctx) {
    Toast.makeText(ctx, "Hi!", Toast.LENGTH_SHORT).show();
}

有时,您必须从另一个Thread向 UI 线程发送消息。 当您无法在 UI 线程上执行网络/IO 操作时,就会发生这种情况。

下面的示例处理这种情况。

  1. 你有 UI 线程
  2. 您必须启动 IO 操作,因此您无法在 UI 线程上运行Runnable 因此,将您的RunnableHandlerThread上的处理程序
  3. Runnable获取结果并将其发送回 UI 线程并显示Toast消息。

解决方案:

  1. 创建一个HandlerThread并启动它
  2. HandlerThread使用Looper创建一个处理程序requestHandler
  3. 从主线程使用 Looper 创建一个处理程序: responseHandler并覆盖handleMessage方法
  4. requestHandlerpost一个Runnable任务
  5. Runnable任务中,在responseHandler上调用sendMessage
  6. 这个sendMessage结果在responseHandler调用handleMessage
  7. Message获取属性并进行处理,更新 UI

示例代码:

    /* 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);
    }

有用的文章:

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

android-looper-handler-handlerthread-i

  1. 获取 UI Thread Handler 实例并使用handler.sendMessage();
  2. 调用post()方法handler.post();
  3. runOnUiThread()
  4. view.post()

您可以使用Looper发送Toast消息。 通过此链接了解更多详情。

public void showToastInThread(final Context context,final String str){
    Looper.prepare();
    MessageQueue queue = Looper.myQueue();
    queue.addIdleHandler(new IdleHandler() {
         int mReqCount = 0;

         @Override
         public boolean queueIdle() {
             if (++mReqCount == 2) {
                  Looper.myLooper().quit();
                  return false;
             } else
                  return true;
         }
    });
    Toast.makeText(context, str,Toast.LENGTH_LONG).show();      
    Looper.loop();
}

它在您的线程中被调用。 Context 可能是Activity.getContext()从你必须展示 toast 的Activity获取。

我根据 mjaggard 回答制定了这种方法:

public static void toastAnywhere(final String text) {
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
        public void run() {
            Toast.makeText(SuperApplication.getInstance().getApplicationContext(), text, 
                    Toast.LENGTH_LONG).show();
        }
    });
}

对我来说效果很好。

带有 runOnUiThread 的 Kotlin 代码

runOnUiThread(
        object : Runnable {
            override fun run() {
                Toast.makeText(applicationContext, "Calling from runOnUiThread()", Toast.LENGTH_SHORT)  
            }
        }
)

我遇到了同样的问题:

E/AndroidRuntime: FATAL EXCEPTION: Thread-4
              Process: com.example.languoguang.welcomeapp, PID: 4724
              java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare()
                  at android.widget.Toast$TN.<init>(Toast.java:393)
                  at android.widget.Toast.<init>(Toast.java:117)
                  at android.widget.Toast.makeText(Toast.java:280)
                  at android.widget.Toast.makeText(Toast.java:270)
                  at com.example.languoguang.welcomeapp.MainActivity$1.run(MainActivity.java:51)
                  at java.lang.Thread.run(Thread.java:764)
I/Process: Sending signal. PID: 4724 SIG: 9
Application terminated.

之前:onCreate 函数

Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        Toast.makeText(getBaseContext(), "Thread", Toast.LENGTH_LONG).show();
    }
});
thread.start();

之后:onCreate 函数

runOnUiThread(new Runnable() {
    @Override
    public void run() {
        Toast.makeText(getBaseContext(), "Thread", Toast.LENGTH_LONG).show();
    }
});

有效。

爪哇11:

var handler = new Handler(Looper.getMainLooper);
handler.post(() -> Toast.makeText(your_context, "Hi!", Toast.LENGTH_SHORT).show());

不过,在 Java 8 中可以使用 Lambda。 var是在 Java 11 中引入的。

与此处几乎所有答案相反, Toast#makeTextToast#show不必在 UI 线程上运行。 唯一的要求是它在一个名为Looper#prepare的线程上运行。

这是因为 toast 是由操作系统处理和呈现的,而不是应用程序。 在内部, Toast#show调用系统服务以将 toast 排队。

这意味着下面的代码是有效的

private static class MyThread extends Thread {
    public Handler handler;

    @Override
    public void run() {
        Looper.prepare();

        handler = new Handler(Looper.myLooper()) {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
            }
        };

        Looper.loop()
    }
}

final private MyThread t = new MyThread();
// start and wait for t to start looping

private void onClick() {
    t.handler.post(() -> Toast.makeText(this, "this works", Toast.LENGTH_SHORT).show());
}

onCreate 中的方法:

private void toastPublic(final String message){
    Handler handler = new Handler(Looper.getMainLooper());
    handler.post(new Runnable() {
       public void run() {
          Toast.makeText(getBaseContext(),""+message, 
             4 /*Toast.LENGTH_SHORT*/).show();
    }});
}

下一步:在线程内部使用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM