gpt4 book ai didi

android - 如何在android中定期更改背景图像

转载 作者:行者123 更新时间:2023-11-29 02:09:43 26 4
gpt4 key购买 nike

在我的 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com