Where The Streets Have No Name

파일 다운로드시 progress dialog를 이용해서 진행률 표시 본문

Developement/Mobile

파일 다운로드시 progress dialog를 이용해서 진행률 표시

highheat 2012. 4. 19. 16:15
public class LayoutDemoActivity extends Activity {

	ProgressDialog mProgressDialog;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		mProgressDialog = new ProgressDialog(LayoutDemoActivity.this);
		mProgressDialog.setMessage("이미지 다운로드");
		mProgressDialog.setIndeterminate(false);
		mProgressDialog.setMax(100);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);

		Button btn2 = (Button) findViewById(R.id.button2);
		btn2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				DownloadFile downloadFile = new DownloadFile();
				downloadFile
						.execute("http://upload.wikimedia.org/wikipedia/commons/thumb/3/32/Japan-qr-code-billboard.jpg/220px-Japan-qr-code-billboard.jpg");
			}
		});
	}

	private String getDownload(String filePath) {
		String saveFilePath = "file:///sdcard/";
		String saveFileName = "download_tempfile.jpg";

		try {
			// set the download URL, a url that points to a file on the internet
			// this is the file to be downloaded
			URL url = new URL(filePath);

			// create the new connection
			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

			// set up some things on the connection
			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);

			// and connect!
			urlConnection.connect();

			// set the path where we want to save the file
			// in this case, going to save it on the root directory of the
			// sd card.
			File SDCardRoot = Environment.getExternalStorageDirectory();
			// create a new file, specifying the path, and the filename
			// which we want to save the file as.
			File file = new File(SDCardRoot, saveFileName);
			saveFilePath += saveFileName;

			// this will be used to write the downloaded data into the file we
			// created
			FileOutputStream fileOutput = new FileOutputStream(file);

			// this will be used in reading the data from the internet
			InputStream inputStream = urlConnection.getInputStream();

			// this is the total size of the file
			int totalSize = urlConnection.getContentLength();
			// variable to store total downloaded bytes
			int downloadedSize = 0;

			// create a buffer...
			byte[] buffer = new byte[1024];
			int bufferLength = 0; // used to store a temporary size of the
									// buffer

			// now, read through the input buffer and write the contents to the
			// file
			while ((bufferLength = inputStream.read(buffer)) > 0) {
				// add the data in the buffer to the file in the file output
				// stream (the file on the sd card
				fileOutput.write(buffer, 0, bufferLength);
				// add up the size so we know how much is downloaded
				downloadedSize += bufferLength;
			}
			// close the output stream when done
			fileOutput.close();

			// catch some possible errors...
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return saveFilePath;
	}

	private class DownloadFile extends AsyncTask<String, Integer, String> {

		@Override
		protected String doInBackground(String... sUrl) {
			try {
				URL url = new URL(sUrl[0]);
				URLConnection connection = url.openConnection();
				connection.connect();
				// this will be useful so that you can show a typical 0-100%
				// progress bar
				int fileLength = connection.getContentLength();

				// download the file
				InputStream input = new BufferedInputStream(url.openStream());
				OutputStream output = new FileOutputStream("/sdcard/download_tempfile.jpg");

				byte data[] = new byte[1024];
				long total = 0;
				int count;
				while ((count = input.read(data)) != -1) {
					total += count;
					// publishing the progress....
					publishProgress((int) (total * 100 / fileLength));
					output.write(data, 0, count);
				}

				output.flush();
				output.close();
				input.close();

				Intent intent = new Intent();
				intent.setAction(Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.parse("file:///sdcard/download_tempfile.jpg"), "image/*");
				startActivity(intent);
			} catch (Exception e) {
			}
			return null;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			mProgressDialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... progress) {
			super.onProgressUpdate(progress);
			mProgressDialog.setProgress(progress[0]);
		}

		@Override
		protected void onPostExecute(String result) {			
			super.onPostExecute(result);
			mProgressDialog.dismiss();
		}

	}
}
위의 소스를 appspresso에서 hybrid방식으로 변환할 경우 asynctask가 제대로 동작하지 않아서 thread 를 이용해서 구현.
public class MyPlugin implements AxPlugin {

	private AxRuntimeContext runtimeContext;
	private String TAG = "Echo";
	private ActivityListener activityListener;
	public static final String ALL_CODE_TYPES = null;
	public static final int REQUEST_CODE_SCAN = 1001;

	ProgressDialog mProgressDialog;
	private final Handler progressUpdateHandler = new Handler();

	@Override
	public void activate(AxRuntimeContext runtimeContext) {
		this.runtimeContext = runtimeContext;
		activityListener = new RuntimeActivityListener(runtimeContext);
		runtimeContext.addActivityListener(activityListener);

		mProgressDialog = new ProgressDialog(runtimeContext.getActivity());
		mProgressDialog.setMessage("이미지 다운로드");
		mProgressDialog.setIndeterminate(false);
		mProgressDialog.setMax(100);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	}

	@Override
	public void deactivate(AxRuntimeContext runtimeContext) {
		this.runtimeContext = null;
		runtimeContext.removeActivityListener(activityListener);
	}

	@Override
	public void execute(AxPluginContext context) {
		String method = context.getMethod();

		if ("echo".equals(method)) {
			scan();
		} else if ("downloadFile".equals(method)) {
			String message = context.getParamAsString(0, null);
			context.sendResult(message);
			threadDownroad("http://upload.wikimedia.org/wikipedia/commons/thumb/3/32/Japan-qr-code-billboard.jpg/220px-Japan-qr-code-billboard.jpg");

		} else {
			context.sendError(AxError.NOT_AVAILABLE_ERR);
		}
	}

	private void scan() {
		Intent iscan = new Intent("com.google.zxing.client.android.SCAN");
		iscan.addCategory(Intent.CATEGORY_DEFAULT);
		runtimeContext.getActivity().startActivityForResult(iscan, REQUEST_CODE_SCAN);
	}

	public void threadDownroad(final String _fileurl) {
		Thread thread = new Thread(new Runnable() {
			public void run() {
				try {
					URL url = new URL(_fileurl);
					HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
					urlConnection.connect();

					InputStream inputStream = urlConnection.getInputStream();
					FileOutputStream fileOutput = new FileOutputStream("/sdcard/download_tempfile.jpg");
					int totalSize = urlConnection.getContentLength();
					int downloadedSize = 0;
					byte[] buffer = new byte[1024];
					int bufferLength = 0; // 임시로 사용할 버퍼의 크기 지정
					while ((bufferLength = inputStream.read(buffer)) > 0) {
						fileOutput.write(buffer, 0, bufferLength);
						downloadedSize += bufferLength;
						updateProgress(downloadedSize, totalSize);
					}
					urlConnection.disconnect();
					inputStream.close();
					fileOutput.close();
					
					Intent intent = new Intent();
					intent.setAction(Intent.ACTION_VIEW);
					intent.setDataAndType(Uri.parse("file:///sdcard/download_tempfile.jpg"), "image/*");
					runtimeContext.getActivity().startActivity(intent);
				} catch (MalformedURLException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		});
		thread.start();
		
	}

	protected void updateProgress(final int downloadedSize, final int totalSize) {
		Runnable updater = new Runnable() {
			public void run() {
				mProgressDialog.setMax(totalSize);
				mProgressDialog.setProgress(downloadedSize);
				if(downloadedSize == totalSize)mProgressDialog.dismiss();
				if(downloadedSize == 1024)mProgressDialog.show();
			}
		};
		progressUpdateHandler.post(updater);		
	}
}