Raising a Toast From AsyncTask

后端 未结 3 1642
日久生厌
日久生厌 2021-01-01 04:23

I\'m trying to raise a toast from asynctask, but I\'m having trouble getting my parameters right. I\'m toasting from onProgressUpdate, so I\'m on the UI thread, which I thi

3条回答
  •  不思量自难忘°
    2021-01-01 04:42

    You can NOT do this in onProgressUpdate(). At least not this way. If Eclipse gives you this error, it is because MainActivity.this is unresolvable for it. Why? Because you are NOT in the UI Thread, so what you do is not thread-safe, because you must not access UI from another Thread.

    First of all, and as told before, you should write a constructor taking a context and saving it to a global variable, so it is accessible everywhere inside the class. Then, to access UI in a thread-safe way, use one of the following:

    Activity.runOnUiThread(Runnable)
    View.post(Runnable)
    View.postDelayed(Runnable, long)
    

    Those are thread-safe.

    Regards

提交回复
热议问题