[Android] DownloadManager 를 이용한 파일 다운로드하기
- Mobile/android
- 2011. 12. 16.
1. AndroidManifest.xml 에 권한 추가하기
<uses-permission android:name="android.permission.ACCESS_ALL_DOWNLOADS"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2. onCreate() 안에 추가하기
// Download - Service
dger = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
// Download - IntentFilter
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
registerReceiver(onNotificationClick, new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED));
3. Handler
BroadcastReceiver onComplete = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
String name = DownQueueMgr.getInstance().GetTextName();
Count++;
Toast.makeText(DownQueue.this, "Count : " + Count, Toast.LENGTH_SHORT).show();
long id = DownQueueMgr.getInstance().GetstateID();
Cursor c= dger.query(new DownloadManager.Query().setFilterById(id));
c.moveToFirst();
int state = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
int reason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
switch(state){
case DownloadManager.STATUS_SUCCESSFUL:
{
if (DownQueueMgr.getInstance().IsTextLastDownloadFile()) {
if( DownQueueMgr.getInstance().IsDownloading() == true )
return;
Handler handler = DownQueueMgr.getInstance().GetHandler();
Message message = handler.obtainMessage();
message.what = DownQueueMgr.FILE_READ_ADD_QUEUE;
message.obj = DownQueueMgr.getInstance().GetTextName();
handler.sendMessage(message);
DownQueueMgr.getInstance().SetDownloading(true);
} else {
if (DownQueueMgr.getInstance().GetQsize() != 0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
Handler handler = DownQueueMgr.getInstance().GetHandler();
Message message = handler.obtainMessage();
message.what = DownQueueMgr.QUEUE_PROCESSING;
handler.sendMessage(message);
}
}
}
break;
case DownloadManager.STATUS_FAILED:
{
switch(reason) {
case DownloadManager.ERROR_FILE_ALREADY_EXISTS:
Log.w("Download", "Error File Already Exists");
break;
default:
Log.w( "Download", "Unknown : " + reason );
break;
}
}
break;
}
//Toast.makeText(DownQueue.this, Count + " : " + name + ", Download Completed!!", Toast.LENGTH_SHORT).show();
}
};
BroadcastReceiver onNotificationClick = new BroadcastReceiver() {
public void onReceive(Context ctxt, Intent intent) {
Toast.makeText( DownQueue.this, "hi!!", Toast.LENGTH_LONG).show();
}
};
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(onComplete);
unregisterReceiver(onNotificationClick);
}
4. File Download 하는 루틴
public long DownloadFile( String url )
{
m_TextName = "";
m_isTextfile = false;
long stateId = -1;
String filePath = "/a_qrcode/";
Uri urlToDownload = Uri.parse(url);
List<String> pathSegments = urlToDownload.getPathSegments();
if( urlToDownload == null )
{
Log.w("Download", "URL Error...!!!!!!!" );
return -1;
}
String file = pathSegments.get(pathSegments.size()-1);
if( file.matches(".*txt.*") ) {
m_TextName = file;
m_isTextfile = true;
m_isDownloaing= false;
}
else {
m_TextName = file;
}
try {
Environment.getExternalStoragePublicDirectory(filePath).mkdirs();
stateId= m_DownloadManager.enqueue(new DownloadManager.Request(urlToDownload)
.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE)
.setAllowedOverRoaming(false)
.setTitle(file)
.setDescription(file + ", Downloaing...")
.setDestinationInExternalPublicDir(filePath,file) );
}catch( Exception e) {
Log.w("Download", "error....log1 " );
}
return stateId;
}
5. 기타 하고 싶은 말
1. Thread 를 이용하면 Toast 가 사용이 불가하다. 안되는 이유는 책들을 참조하길 바람.
2. Thread 를 사용하지 않으면 어떻게 사용할 것인가!? Handler 를 사용하는 것이다.
3. Handler 를 사용하는 방법은 책을 참조!(인터넷 뒤져서 알면...?? 머리속에 들어갈까!?)
4. Overlap IO 를 DownloadManager 는 지원을 하지 않는 것 같다. 뭐 순차적이든 어떻게든 다운이 되어지긴 하지만, 상황에따라서 되고 안되고...차이가 많은 것 같다.
바쁘니깐 정리는 요까지만 하자.
기타 Reference
추가되는 내용
// 아래 추가!
<uses-permission android:name="android.permission.ACCESS_ALL_DOWNLOADS"></uses-permission>
http://gitorious.org/rowboat/frameworks-base/blobs/65c36e6133be04e008bc164b62d42884ff06a13a/core/tests/coretests/src/android/app/DownloadManagerIntegrationTest.java
http://www.java2s.com/Open-Source/Android/android-core/platform-frameworks-base/android/app/DownloadManagerBaseTest.java.java-doc.htm
// 여기서 무슨 파일을 다운 받음.
https://gist.github.com/CyanogenMod/android_frameworks_base/downloads
자바에서 이런것도 제공하는건가..ㄸ
http://www.java2s.com/Code/Android/CatalogAndroid.htm
http://www.java2s.com/Open-Source/Android/android-core/platform-frameworks-base/android.app.htm
// 추가!
http://toriworks.tistory.com/218
http://stbaeya.com/tc/219?TSSESSIONstbaeyacomtc=4db60f017c891d0d506fa774286c6f1c
// 그냥 파일 다운로드 하는 거
http://journae.springnote.com/pages/5947557?print=1
'Mobile > android' 카테고리의 다른 글
Android NDK 경로 저장(windows, ubuntu ) (0) | 2011.12.20 |
---|---|
[Android] JNI TIP, udev (0) | 2011.12.20 |
[android sensor] TYPE_ROTATION_VECTOR (0) | 2011.12.08 |
[NDK build] Android.mk Application.mk (0) | 2011.12.07 |
....3D engine(Irrlicht) on android (0) | 2011.11.13 |