본문 바로가기

Programming/Android

[Android, Hybrid] 앱에서 파일 다운로드 구현. URL File Download.

웹브라우저를 이용해서 파일을 다운로드 받을 경우, 다운로드매니저를 통해 받게 된다.(진저브레드 이상)


앱에서 다운로드 매니저를 사용하여 파일 다운로드 받는 방법을 쓰고자 한다.


앱이나 하이브리드나 다운로드 하는 방법은 동일하다.


다운로드 매소드, 그리고 다운로드매니저로부터 액션을 받을 수 있는 리시버를 만드면 끝.!


Download Method

private DownloadManager mDownloadManager; //다운로드 매니저. 
private int mDownloadQueueId; //다운로드 큐 아이디..
private String mFileName ; //파일다운로드 완료후...파일을 열기 위해 저장된 위치를 입력해둔다.
/**
 * @param url : 파일을 다운로드할 url.
 */
public void download(String url) {
	if (mDownloadManager == null) {
		mDownloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
	}
	Request request = new DownloadManager.Request( Uri.parse(url) );
	request.setTitle("==타이틀==");
	request.setDescription("==설명==");
	List<string> pathSegmentList = uri.getPathSegments();
	Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/temp").mkdirs();  //경로는 입맛에 따라...바꾸시면됩니다.
	request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS + "/temp/", pathSegmentList.get(pathSegmentList.size()-1) );
	mFileName = pathSegmentList.get(pathSegmentList.size()-1);

	mDownloadQueueId = mDownloadManager.enqueue(request);
}



다운로드관련 인텐트를 받을 리시버를 만들고, 등록시켜주면 끝!

(onResume 에서 등록, onPause에서 해제를 추천한다.)


Complete Receiver

/**
 * 다운로드 완료 액션을 받을 리시버.
 */
private BroadcastReceiver mCompleteReceiver = new BroadcastReceiver() {
	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
			Toast.makeText(context, "Complete.", Toast.LENGTH_SHORT).show();
			Intent intent1 = new Intent();
			intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			intent1.setAction(android.content.Intent.ACTION_VIEW);
			intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

			String localUrl = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
					+ "/temp/" + mFileName; //저장했던 경로..
			String extension = MimeTypeMap.getFileExtensionFromUrl(localUrl);
			String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);

			File file = new File(localUrl);
			intent1.setDataAndType(Uri.fromFile(file), mimeType);
			try {
				startActivity(intent1);
			} catch (ActivityNotFoundException e) {
				Toast.makeText(NPF.this, "Not found. Cannot open file.", Toast.LENGTH_SHORT).show();
				e.printStackTrace();
			}
		}
	}
};


@Override
protected void onPause() {
	super.onPause();
	unregisterReceiver(mCompleteReceiver);
}

@Override
protected void onResume() {
	super.onResume();
	IntentFilter completeFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
	registerReceiver(mCompleteReceiver, completeFilter);
}


하이브리드 앱의 경우 JavaInterface에 해당 method를 넣어주면 되고, 일반적인 앱에서 사용할 경우에는


유틸 같은 곳에 추가하여 사용하면된다.(물론 해당 method를 조금 수정해서 context를 받도록 해야할 것이긴 하지만)