如何在AsyncTask中举杯祝酒,系统提示我使用Looper
我的任务由AsyncTask在后台完成。在某些时候,我需要发布Toast来完成一些事情。如何在AsyncTask中举杯祝酒,系统提示我使用Looper
我试过,我失败了,因为 Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
我怎么能这样做?
onPostExecute - 在UI线程上执行 或 publishProgress()
;在doinbackground和
protected void onProgressUpdate(Integer... progress) {
}
http://developer.android.com/reference/android/os/AsyncTask.html
您还可以使用runOnUiThread方法从后台线程操作你的UI。
为什么投票?我认为他必须调用runOnUiThread。 – 2010-05-14 22:48:56
适合我。只需要调用getActivivty()。runOnUiThread(...) – demula 2013-08-12 10:21:41
如果您想从后台线程显示Toast,您必须从doInBackground调用runOnUiThread。我不相信有另一种方式。
编辑:我收回。我认为你可以实现在UI线程上运行的onProgressUpdate来显示Toast并从doInBackground调用publishProgress。
如果你想使用吐司 你应该使用这种方法:onProgressUpdate()
protected Integer doInBackground(Void...Params) {
int check_point = 1;
publishProgress(check_point);
return check_point;
}
protected void onProgressUpdate(Integer integers) {
if(integers == 1) {
Toast.makeText(classname.this, "Text", 0).show();
}
可以在里面doInBackground
添加以下代码要吐司出现
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(<your class name>.this, "Cool Ha?", Toast.LENGTH_SHORT).show();
}
});
敬酒
谢谢!这正是我所期待的。 – 2017-03-20 12:22:04
如果要在doInBackground中显示Toast,可以在AsyncTask的OnPostExecute方法中使用它。
protected void onPostExecute(String file_url) {
Toast.makeText(getApplicationContext(),"Your Message", Toast.LENGTH_LONG).show();
pDialog.dismiss();//dismiss the progress dialouge
}
我必须在过程中间发出Toast,而不是结束。我有什么选择? – Pentium10 2010-05-14 22:03:00
onProgressUpdate。它也运行在UI线程和Toast应该罚款 – 2010-05-15 21:13:14
-1 downvoted,因为这个问题的每个其他答案比这个更好! – necromancer 2014-08-22 03:09:47