为了账号安全,请及时绑定邮箱和手机立即绑定

无法在未调用Looper.prepare()的线程内创建处理程序

无法在未调用Looper.prepare()的线程内创建处理程序

MMMHUHU 2019-05-29 15:39:49
无法在未调用Looper.prepare()的线程内创建处理程序以下例外意味着什么; 我该怎么解决?这是代码:Toast toast = Toast.makeText(mContext, "Something", Toast.LENGTH_SHORT);这是例外:java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()      at android.os.Handler.<init>(Handler.java:121)      at android.widget.Toast.<init>(Toast.java:68)      at android.widget.Toast.makeText(Toast.java:231)
查看完整描述

3 回答

?
狐的传说

TA贡献1804条经验 获得超3个赞

你是从工作线程调用它。您需要Toast.makeText()从主线程中调用(以及处理UI的大多数其他函数)。例如,您可以使用处理程序。

查找文档中的UI线程进行通信。简而言之:

// Set this up in the UI thread.mHandler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(Message message) {
        // This is where you do your work in the UI thread.
        // Your worker tells you in the message what to do.
    }};void workerThread() {
    // And this is how you call it from the worker thread:
    Message message = mHandler.obtainMessage(command, parameter);
    message.sendToTarget();}

其他选择:

您可以使用AsyncTask,它适用于在后台运行的大多数事情。它有一些钩子,您可以调用它来指示进度,以及何时完成。

您还可以使用Activity.runOnUiThread()


查看完整回答
反对 回复 2019-05-29
  • 3 回答
  • 0 关注
  • 1028 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信