gpt4 book ai didi

java - 安卓下载镜像

转载 作者:行者123 更新时间:2023-12-01 13:35:09 28 4
gpt4 key购买 nike

我正在尝试连续从网络服务器下载图像。下面显示的是代码

public class HMIActivity extends Activity implements Observer{

private ImageView imageView;

public HMIActivity()
{

}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hmi);
}

@Override
protected void onStart()
{
super.onStart();
ImageDownloader imageDownloader = new ImageDownloader("http://192.168.5.109/hmi/img.jpg",this);
Thread thread = new Thread(imageDownloader);
thread.start();

imageView = (ImageView) findViewById(R.id.imageView1);

}
public void update(Observable obj,Object data)
{
HTTPCommunicator httpCommunicator = (HTTPCommunicator)data;
System.out.println("length----"+httpCommunicator.bytes.length);

}

图像下载器类的代码

public class ImageDownloader implements Runnable{

private final String urlToDownloadImage;
private HMIActivity hmiActivity;
private int NTHREADS = 10;
ExecutorService executor = Executors.newFixedThreadPool(NTHREADS);

public ImageDownloader(String url,HMIActivity _hmiActivty)
{
this.urlToDownloadImage = url;
hmiActivity = _hmiActivty;
}

@Override
public void run(){

while(true){
HTTPCommunicator httpCommunicator = new HTTPCommunicator(this.urlToDownloadImage);
httpCommunicator.addObserver(this.hmiActivity);
executor.execute(httpCommunicator);
}
}
}

htppcommunicator 类的代码

public class HTTPCommunicator extends Observable implements Runnable {

String urlToDownloadImage;
private final int HTTP_CONNECTION_TIMEOUT = 10*1000;
public byte bytes[];

public HTTPCommunicator(String urlToDownloadImage)
{
this.urlToDownloadImage = urlToDownloadImage;
}

@Override
public void run() {
// TODO Auto-generated method stub

try
{
URL url = new URL(urlToDownloadImage);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(HTTP_CONNECTION_TIMEOUT);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
if(inputStream != null)
{
bytes = IOUtils.toByteArray(inputStream);

setChanged();
notifyObservers(this);
}
}
catch(MalformedURLException _exception)
{
Log.e("HTTPCommunicator","Malformed url exception");
}
catch(UnknownHostException _exception)
{
Log.e("HTTPCommunicator","Check Internet Connection!!!");
}
}
}

此代码仅运行正常 1 分钟,然后抛出以下所示的异常

01-24 12:50:15.379: E/AndroidRuntime(912): FATAL EXCEPTION: pool-1-thread-7
01-24 12:50:15.379: E/AndroidRuntime(912): java.lang.OutOfMemoryError

我不知道如何解决这个问题。请帮助我。

最佳答案

好吧,不要手动下载图像,而是尝试延迟加载图像..对于延迟加载,android 中有很多选项

1. UIL

2 Android Smart Image View

所以你不会出现内存不足的异常..

关于java - 安卓下载镜像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21339569/

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