matghazaryan
matghazaryan

Reputation: 5896

create persistent connection

In my android application I am trying create persistent connection for downloading images. Here is my code

 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();
        }
    }

When I start download the file every time it should open connection for download, I want to open connection only one time and when the application end downloading all files the connection must be disconnected. Is there any way to do this.

Thanks anyone who get attention on this.

Upvotes: 0

Views: 154

Answers (1)

Grims
Grims

Reputation: 807

Http connections are "stateless" so there is no connection to be kept open like say in an SSH connection; So each image you download will be done in a separate request/connection. (that's also the web browser do it).

Also, why did you put the creation of the URL in a separate try/catch ? That makes no sense because if you fail to create the URL object, you will get a null pointer when you will try to open the connection.

Upvotes: 1

Related Questions