【问题标题】:App crashing while returning from AsyncTask doInBackground [duplicate]从 AsyncTask doInBackground 返回时应用程序崩溃 [重复]
【发布时间】:2018-12-19 00:32:46
【问题描述】:

[抱歉英语不好]

大家好, 在这里,我尝试在异步任务中执行某些操作,并且应用程序在运行时崩溃。当它到达返回线时,应用程序就会死掉。

这是我的代码

private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
    protected Void doInBackground(Void... params){
        velocidadMedia = (distanciaTotal)/(tiempoTotal);
        track = new TrackItem(  sdf.format(new Date()),
                Double.toString((int) distanciaTotal),
                Double.toString((int) tiempoTotal),
                Double.toString((int) velocidadMedia));
        String IDFromServer = databaseReference.push().getKey();
        track.setKey(IDFromServer);
        databaseReference.child(IDFromServer).setValue(track);
        Toast.makeText(getContext(),"Track Creado!", Toast.LENGTH_LONG).show();
        return null;
    }

}

知道这个异步任务在片段内可能很有用。

Android Studio 在错误日志中给了我这个:

原因:java.lang.RuntimeException: Can't create handler inside 没有调用 Looper.prepare() 的线程

我尝试使用没有说明的onPostExecute 方法,但没有解决问题。

【问题讨论】:

    标签: android android-asynctask


    【解决方案1】:

    您不能从后台线程调用Toast.makeText()。您只能从 UI/主线程调用。将Toast.makeText() 调用移至onPostExecute()

    【讨论】:

    • 将 toast 移动到 onPostExecute 时不起作用。最后将其移至主线程。还是谢谢!
    【解决方案2】:

    来自:Can't create handler inside thread that has not called Looper.prepare()

    您从工作线程调用它。您需要从主线程中调用 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()

    【讨论】:

      【解决方案3】:

      doInBackground() 中无法显示 toast 消息

      Toast.makeText(getContext(),"Track Creado!", Toast.LENGTH_LONG).show();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-14
        • 2023-03-21
        相关资源
        最近更新 更多