프로그램/Android

안드로이드 AsyncTask를 이용하여 파일 다운로드

잡식성초보 2016. 9. 7. 13:17

AsyncTask를 이용하여 이미지 파일 다운로드 하기...


좀더 추가해 줘야할것은 같은 이름의 파일이 있을때의 처리...


나같은경우는 원래 파일명을 시간날짜이런걸 뒤에 붙여 만들었으므로


그럴 경우가 없기애...



    private class ImageDownload extends AsyncTask<String, Integer, String> {        //이미지 다운로드

        private String fileName;
        String savePath = Environment.getExternalStorageDirectory() + File.separator + "temp/";
        
        @Override
        protected void onPreExecute() {

            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {

            File dir = new File(savePath);
            //상위 디렉토리가 존재하지 않을 경우 생성
            if (!dir.exists()) {
                dir.mkdirs();
            }

            String fileUrl = params[0];

            String localPath = savePath + "/" + fileName + ".jpg";

            try {
                URL imgUrl = new URL(fileUrl);
                //서버와 접속하는 클라이언트 객체 생성
                HttpURLConnection conn = (HttpURLConnection) imgUrl.openConnection();
                int response = conn.getResponseCode();

                File file = new File(localPath);

                InputStream is = conn.getInputStream();
                OutputStream outStream = new FileOutputStream(file);

                byte[] buf = new byte[1024];
                int len = 0;

                while ((len = is.read(buf)) > 0) {
                    outStream.write(buf, 0, len);
                }

                outStream.close();
                is.close();
                conn.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String obj) {

            //저장한 이미지 열기
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            String targetDir = Environment.getExternalStorageDirectory().toString();

            File file = new File(targetDir + "/" + fileName + ".jpg");

            //type 지정 (이미지)
            i.setDataAndType(Uri.fromFile(file), "image/*");
            mContext.startActivity(i);

            super.onPostExecute(obj);

        }
    }


반응형