在我的 android 应用程序中,我需要在 10 秒内更改 ImageView 中的背景图像一次。这样我就可以在运行方法中调用异步任务。当我执行应用程序时它崩溃了。
它给我 Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
异常。
我知道我必须使用 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;
}
}
最佳答案
您正在从工作线程调用 AsyncTask。这样它就无法访问 UI 线程。您可能应该考虑使用处理程序。
关于android - 如何在android中定期更改背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8183038/