【发布时间】:2011-11-18 13:18:59
【问题描述】:
在我的 android 应用程序中,我需要在 10 秒内更改图像视图中的背景图像。以便我在运行方法中调用异步任务。当我执行应用程序时它崩溃了。
它给了我Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() Exception。
我知道我必须使用 Thread,但我不知道如何正确使用。请帮帮我。
这是我的代码示例:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
.................
new Thread()
{
public void run()
{
while(true){
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
count = count + 1;
new ImageChange().execute();
}
}
}.start();
} // OnCreate End
class ImageChange extends AsyncTask<Void, Void, Void>
{
protected void onPreExecute() {
}
protected void onPostExecute(Void unused) {
iv1.setImageBitmap(b1);
iv2.setImageBitmap(b2);
}
protected Void doInBackground(Void... arg0) {
switch(count){
case 1:
b1 = BitmapFactory.decodeFile(f1.getAbsolutePath());
b2 = BitmapFactory.decodeFile(f2.getAbsolutePath());
break;
case 2:
b1 = BitmapFactory.decodeFile(f2.getAbsolutePath());
b2 = BitmapFactory.decodeFile(f1.getAbsolutePath());
break;
default :
count = 0;
b1 = BitmapFactory.decodeFile(f1.getAbsolutePath());
b2 = BitmapFactory.decodeFile(f2.getAbsolutePath());
break;
}
return null;
}
}
【问题讨论】:
-
好的,在我调查你的问题之前,有几件事让我印象深刻:(1)在将它们设置为其他值之前无需将 b1 和 b2 设置为 null,这没有特殊效果。 (2) 在Java中命名一个类的好方法是使用CamelCase:将其命名为ImageChange而不是imagechange
标签: android android-imageview android-image android-asynctask