从我的线程执行时,Acitivity 会忽略显示 Toast
为什么我只看到“第一个”toast,而看不到从我的线程创建的其他(应该)toast?
public class BannerExample extends Activity {
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast toast = Toast.makeText(this, "first toast", Toast.LENGTH_SHORT);
toast.show();
new MyThread(this).start();
}
class MyThread extends Thread {
private Context context;
public MyThread(Context context) {
this.context = context;
}
public void run() {
Looper.prepare(); // An exception told me to add this - i have no clue why
for (int i = 0; i < 3; i++) {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Toast toast = Toast.makeText(context, i + "whoho", Toast.LENGTH_SHORT);
toast.show();
}
}
}
}
Why do I only see the "first" toast and not the others (should be) created from my thread?
public class BannerExample extends Activity {
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast toast = Toast.makeText(this, "first toast", Toast.LENGTH_SHORT);
toast.show();
new MyThread(this).start();
}
class MyThread extends Thread {
private Context context;
public MyThread(Context context) {
this.context = context;
}
public void run() {
Looper.prepare(); // An exception told me to add this - i have no clue why
for (int i = 0; i < 3; i++) {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Toast toast = Toast.makeText(context, i + "whoho", Toast.LENGTH_SHORT);
toast.show();
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Looper.prepare
。您收到异常是因为您做错了什么:Thread
对于AsyncTask
并利用 < code>onProgressUpdate 方法来创建 Toast,因为它会自动在 UI 线程上运行。否则,您将需要使用处理程序。getBaseContext
传递到构造函数,而不是从当前活动的上下文Looper.prepare
. You were getting the exception because you were doing something wrong:Thread
forAsyncTask
and make use of theonProgressUpdate
method to create your toasts as this automatically runs on the UI thread. Otherwise you'll need to use a handler.getBaseContext
rather than the context from the current activity to your constructor