当有人通过我的应用程序工作时,我正在尝试在后台加载图像。我写的逻辑是这样的:
public class ImageLoader extends AsyncTask <Context, Void, Bitmap>{
private String URL;
private int type;
ImageLoader(String Url, int Type)
{
URL = Url;
type = Type;
}
@Override
protected Bitmap doInBackground(Context... arg0) {
AssetManager assetMgr = arg0[0].getAssets();
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeStream(assetMgr.open(URL));
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute( Bitmap result ) {
super.onPostExecute(result);
if (type == 1)
Inst1 = result;
else if (type == 2)
Inst2 = result;
else if (type == 3)
Inst3 = result;
}
}
但是,当我尝试像这样开始一个新线程时:
task = new ImageLoader("Instructions_2.png", 3);
task.execute(gameContext);
但是在程序中我得到错误 Looper.prepare 必须被调用,然后是逻辑 looper.quit()
但是,当我添加 Looper.prepare() 时,我似乎破坏了程序,并且没有 looper.quit() 可以调用。
我是否正确创建任务?
编辑:
这是我尝试运行时的错误日志:
task = new ImageLoader(gameContext, "Instructions_3.png", 3);
我有一个 switch case 语句,我将图像加载器声明放在外面。基本上我的代码是:
ImageLoader task;
switch(foo)
{
case 0:
...
task = new ImageLoader(gameContext, "Instructions_0.png", 3);
task.execute();
break;
case 1:
...
task = new ImageLoader(gameContext, "Instructions_1.png", 3));
task.execute();
break;
...
}
和错误日志(每次我打task = new ImageLoader(...);
线时都会发生错误
07-20 14:23:34.276: E/AndroidRuntime(16741): FATAL EXCEPTION: Thread-10
07-20 14:23:34.276: E/AndroidRuntime(16741): java.lang.ExceptionInInitializerError
07-20 14:23:34.276: E/AndroidRuntime(16741): at com.petronicarts.stormthecastle.MainGamePanel.update(MainGamePanel.java:2578)
07-20 14:23:34.276: E/AndroidRuntime(16741): at com.petronicarts.stormthecastle.MainThread.run(MainThread.java:63)
07-20 14:23:34.276: E/AndroidRuntime(16741): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
07-20 14:23:34.276: E/AndroidRuntime(16741): at android.os.Handler.<init>(Handler.java:121)
07-20 14:23:34.276: E/AndroidRuntime(16741): at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
07-20 14:23:34.276: E/AndroidRuntime(16741): at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
07-20 14:23:34.276: E/AndroidRuntime(16741): at android.os.AsyncTask.<clinit>(AsyncTask.java:152)
07-20 14:23:34.276: E/AndroidRuntime(16741): ... 2 more