다운로드 프로그램을 만들었는데 프로그레스바가 너무 빨리 100%가 되어서 한참후에 다운로드완료라는 메시지가 표시가 됩니다
프로그레스바 움직임을 느리게 할수 없을까요?
=================================================================================================
class ExampleAsyncTask extends AsyncTask<String, Integer, Long> {
@Override
protected void onCancelled() {
super.onCancelled();
}
@Override
protected void onPostExecute(Long result) {
Toast.makeText(UpdateActivity.this, "다운 완료", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
pb.setProgress(values[0]);
super.onProgressUpdate(values);
}
@Override
protected Long doInBackground(String... params) {
long result = 0;
int numberOfParams = params.length;
try
{
URL url = new URL("http://xxx.xxx.xxx.xx/test.apk");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.connect();
Log.e("DOWNLOAD", "Connect");
File SDCardRoot = Environment.getExternalStorageDirectory();
File file = new File(SDCardRoot,"test.apk");
FileOutputStream fileOutput = new FileOutputStream(file);
Log.e("DOWNLOAD", "fileoutput");
InputStream inputStream = urlConnection.getInputStream();
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
fileOutput.write(buffer, 0, bufferLength);
publishProgress((int) ((bufferLength / (float) numberOfParams) * 10));
}
fileOutput.close();
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
return result;
}
}
publishProgress의 계산식이 잘못된것 같습니다.
//건방진프로그래머
AsyncTask를 excute후에는 콜백메서드가 UI스레드에서 호출되기 때문에 핸들러가 필요없습니다...
AsyncTask 내부에서 publishProgress호출할때 UI스레드에서 onProgressUpdate가 호출됩니다.
onProgressUpdate자체가 핸들러인 셈이지요...
이너 클래스로 만들면 그냥 바로 변경할 UI인스턴스에 접근하면 되구요
따로 정의되어 있다면 생성자에서 건네주면 됩니다.
그래서 제약 사항이 UI스레드 에서 인스턴스를 생성해야하죠...
AsyncTask내에서 핸들러를 쓴다는건 그냥 Thread보다 더 어려운 Thread를 쓸뿐이죠....




이런경우
bufferlength를 누적해주는 별도 변수를 두고 (transferedlLength) 라 하지요
그다음 transferedLength / totalSize 로 해야할것같네요