본문 바로가기

안드로이드

파일다운로드

반응형

public class DownloadFileAsync extends AsyncTask<String, String, String> {


private ProgressDialog mDlg;

private Context mContext;


public DownloadFileAsync(Context context) {

mContext = context;

}


@Override

protected void onPreExecute() {

mDlg = new ProgressDialog(mContext);

mDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

mDlg.setMessage("다운로드 시작");

mDlg.show();


super.onPreExecute();

}


@Override

protected String doInBackground(String... params) {

publishProgress("max", Integer.toString(100));


int count = 0;


try {

Thread.sleep(100);

URL url = new URL(params[0].toString());

URLConnection conexion = url.openConnection();

conexion.connect();


int lenghtOfFile = conexion.getContentLength();

String folderPath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/hellofEnglish/";

String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()+"/hellofEnglish/" + "bb.mp3";

File folder = new File(folderPath);

if (folder.exists()) {

} else {

folder.mkdirs();

}



InputStream input = new BufferedInputStream(url.openStream());

OutputStream output = new FileOutputStream(

filePath);


byte data[] = new byte[1024];


long total = 0;


while ((count = input.read(data)) != -1) {

total += count;

publishProgress("progress" ,Integer.toString((int) ((total * 100) / lenghtOfFile)));

output.write(data, 0, count);

}


output.flush();

output.close();

input.close();


// 작업이 진행되면서 호출하며 화면의 업그레이드를 담당하게 된다


} catch (InterruptedException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}


// 수행이 끝나고 리턴하는 값은 다음에 수행될 onProgressUpdate 의 파라미터가 된다

return null;

}


@Override

protected void onProgressUpdate(String... progress) {

if (progress[0].equals("progress")) {

mDlg.setProgress(Integer.parseInt(progress[1]));

} else if (progress[0].equals("max")) {

mDlg.setMax(Integer.parseInt(progress[1]));

}

}


@SuppressWarnings("deprecation")

@Override

protected void onPostExecute(String unused) {

mDlg.dismiss();

// Toast.makeText(mContext, Integer.toString(result) + " total sum",

// Toast.LENGTH_SHORT).show();

}

}

반응형

'안드로이드' 카테고리의 다른 글

안드로이드 네이버 로그인  (0) 2015.10.14
Cannot merge new index 65608 오류  (0) 2015.09.02
안드로이드 진동과 소리  (0) 2015.08.06
안드로이드 페이스북 4.0 로그인  (1) 2015.07.17
ArrayList 썩기  (0) 2015.05.12