我有一个应用程序,该应用程序使用URL将图像加载到位图中,最近收到了来自Android 2.2.1的用户的电子邮件,该用户在无法加载某些图像时遇到了麻烦。我尝试环顾四周,似乎找不到未加载的图像之间的任何连接。此外,有时不会为她加载的图像会重新开始工作,就像没有任何问题一样。我从未听说过任何更高版本的Android会出现此问题,因此我认为这是2.2.1特有的问题。如果有人可以向我解释发生了什么问题以及(如果可能的话)如何解决问题,我将不胜感激。
以下是相关代码:
public class htmlGrabber extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... params) {
try {
return getHtml();
}
catch (IOException e) {
problem();
return null;
}
}//end of doInBackground
@Override
protected void onPostExecute(String result){
Loading.fa.finish();
shared_preferences=getSharedPreferences("shared_preferences_test", MODE_PRIVATE);
shared_preferences_editor = shared_preferences.edit();
shared_preferences_editor.putString("url_key", current);
shared_preferences_editor.commit();
TouchImageView img = (TouchImageView) findViewById(R.id.img);
img.setImageBitmap(bitmap);
}
}
public String getHtml() throws IllegalStateException, IOException{
//gets html from the url stored in current, then parses through it and extracts the image url, then converts
//it into a bitmap image
String html = "";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(current);
HttpResponse response = client.execute(request);
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();
/* Edited out the code that parses through the HTML looking for the image URL. The image URL is stored in the string "link"
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(link).getContent());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return html;
}//end of getHtml
}//end of htmlGrabber
如果您需要任何澄清,请告诉我!
最佳答案
当您尝试使用Android 2.2.1时,也会遇到此问题?
具体什么时候?
因为如果此AsyncTask
被某个活动作为午餐,则取决于该活动(如果更改方向或其他操作,则该任务将被杀死并再次被午餐),并且可能是此行为在她的手机中无法正常工作。 ..并且最好考虑缓存图片...
您还可以看到此question,它解释了Android中AsyncTask
定义的更多问题,以及该定义已更改了多少次;因此正常情况下,每个版本的工作方式都不相同。
他们在documentation中说:
首次引入时,AsyncTasks在单个后台线程上串行执行。从DONUT开始,它已更改为线程池,允许多个任务并行运行。从HONEYCOMB开始,任务将返回到在单个线程上执行,以避免由并行执行引起的常见应用程序错误。如果您确实想要并行执行,则可以将此方法的executeOnExecutor(Executor,Params ...)版本与THREAD_POOL_EXECUTOR一起使用;但是,请参阅此处的注释以获取有关其使用的警告。
API级别11(Android 3.0.x,HONEYCOMB)中同时添加了executeOnExecutor()和THREAD_POOL_EXECUTOR。
->这意味着,如果创建两个AsyncTasks来下载两个文件,则直到第一个下载完成后,第二个下载才会开始。如果您通过两台服务器聊天,而第一台服务器已关闭,则在连接第一个服务器超时之前,您将无法连接到第二个服务器。 (当然,除非您使用新的API11功能,但这会使您的代码与2.x不兼容)。
而且,如果您希望同时针对2.x和3.0+,那么这些东西将变得非常棘手。
我建议以universal image loader为例,这是一个很好的,“著名的”且非常简单的API,用于加载图片和自动处理缓存...
实际上,我正在使用Universal Image Loader。解决方案与缓存的事实无关,但与该Loader的实例与活动的上下文无关(其方法相关,但通过缓存它们处理活动的生命周期),这一事实意味着,您的任务不会被Activity的onDestroy()完全杀死并重新启动。您可以打开它的实例,然后对所有应用程序使用它的方法。当您想杀死该实例时,您可以调用它自己的Destroy。
我不能说,这是否可以肯定地解决您的问题。我认为您也无需测试也无法回答...但是可能会解决其他问题...
我希望我能帮助...