Raising a Toast From AsyncTask

后端 未结 3 1625
日久生厌
日久生厌 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

    0 讨论(0)
  • 2021-01-01 05:02

    If it's not an inner class declared at the point of use then MainActivity.this is likely to be out of scope. The only way to remedy the problem is to subclass AsyncTask and change the constructor to accept a context variable so you can set it in your custom class and use it from methods. Using getApplicationContext might work as well but I'm not sure how it will behave.

    0 讨论(0)
  • 2021-01-01 05:05

    Get the Context object by calling getApplicationContext() from MainActivity and pass it as a parameter to your AsyncTask. As EboMike has pointed out, MainActivity.this would only work if your AsyncTask was an inner class.

    0 讨论(0)
提交回复
热议问题