在我的 android 应用程序中,我正在尝试为下载图像创建持久连接。这是我的代码
public class PersActivity extends Activity {
ImageView img;
String imageUrl="http://192.168.1.4/JRec/";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button bt3= (Button)findViewById(R.id.download);
bt3.setOnClickListener(getImgListener);
img = (ImageView)findViewById(R.id.image);
}
View.OnClickListener getImgListener = new View.OnClickListener()
{
@Override
public void onClick(View view) {
for (int i = 0; i<4;i++){
downloadFile(i,imageUrl+"images/"+i+".png");
}
}
};
Bitmap bmImg;
void downloadFile(int i, String fileUrl){
URL myFileUrl =null;
try {
myFileUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
System.out.println("Opening connection");
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setRequestProperty("Connection", "keep-alive");
conn.setDoInput(true);
conn.connect();
System.out.println("Downloading"+fileUrl);
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
img.setImageBitmap(bmImg);
if (i ==3){
System.out.println("Disconnected");
conn.disconnect();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
当我每次开始下载文件时,它应该打开连接进行下载,我只想打开一次连接,当应用程序结束下载所有文件时,连接必须断开。有没有办法做到这一点。
感谢任何关注此问题的人。