프로그램/Android

안드로이드 Download Manager

잡식성초보 2016. 9. 7. 13:08

안드로이드 다운로드 매니저를 이용한 파일 다운로드....


리시버를 등록하여 줘서 사용하는것...

private long mDownloadReference;
private DownloadManager mDownloadManager;
private BroadcastReceiver receiverDownloadComplete;    //다운로드 완료 체크
private BroadcastReceiver receiverNotificationClicked;    //다운로드 시작 체크

if (mDownloadManager == null) {
    mDownloadManager = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
}

Uri uri = Uri.parse(data);        //data는 파일을 떨궈 주는 uri 
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setTitle("파일다운로드");    //다운로드 완료시 noti에 제목

request.setVisibleInDownloadsUi(true);
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
//모바일 네트워크와 와이파이일때 가능하도록
request.setNotificationVisibility( DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//다운로드 완료시 noti에 보여주는것
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS + "/temp", "이미지파일.jpg");
//다운로드 경로, 파일명을 적어준다

mDownloadReference = mDownloadManager.enqueue(request);

IntentFilter filter = new IntentFilter(DownloadManager.ACTION_NOTIFICATION_CLICKED);

receiverNotificationClicked = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

String extraId = DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS;
long[] references = intent.getLongArrayExtra(extraId);
for (long reference : references) {
 
        }
    }
};

 mContext.registerReceiver(receiverNotificationClicked, filter);


IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);

receiverDownloadComplete = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

    long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);

    if(mDownloadReference == reference){

    DownloadManager.Query query = new DownloadManager.Query();
    query.setFilterById(reference);
    Cursor cursor = mDownloadManager.query(query);

    cursor.moveToFirst();

   int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
   int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);

   int status = cursor.getInt(columnIndex);
   int reason = cursor.getInt(columnReason);

   cursor.close();

   switch (status){

   case DownloadManager.STATUS_SUCCESSFUL :

       Toast.makeText(mContext, "다운로드 완료.", Toast.LENGTH_SHORT).show();
       break;

  case DownloadManager.STATUS_PAUSED :

       Toast.makeText(mContext, "다운로드 중지 : " + reason, Toast.LENGTH_SHORT).show();
       break;

  case DownloadManager.STATUS_FAILED :

       Toast.makeText(mContext, "다운로드 취소 : " + reason, Toast.LENGTH_SHORT).show();
       break;
    }
 }
}
};

mContext.registerReceiver(receiverDownloadComplete, intentFilter);


반응형