DownloadManager

DownloadManager

DownloadManager

필요한 권한

파일을 다운로드받고 읽기/쓰기 위해서는 다음 권한이 필요한다.
  • 인터넷 접속 권한.
    • android:permission.INTERNET
  • 저장 매체 읽기 권한.
    • android.permission.READ_EXTERNAL_STORAGE
  • 저장 매체 쓰기 권한.
    • android.permission.WRITE_EXTERNAL_STORAGE

DownloadManager

  • 안드로이드 시스템 서비스.
    • DownloadManager downdloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
  • API 9 부터 지원.
  • 다운로드 내용이 notification으로 표시된다.
  • 각각의 다운로드는 (long) id로 구분된다.
  • 다운로드를 요청하기 위해서는 Request를 만들고 DownloadManager에 enqueue()를 호출한다.
  • 다운로드의 완료 여부시 알림을 받기 위해서는 Broadcast Receiver를 등록해야 한다.
    • DownloadManager.ACTION_DOWNLOAD_COMPLETE

DownloadManager.Request

  • 다운로드할 uri를 생성자의 인자로 설정.
    • DownloadManager.Request(Uri uri)
  • 다운로드한 파일을 저장할 위치 지정.
    • Environment.DIRECTORY_DOWNLOADS : default 다운로드 위치
  • 표시되 Notification의 title, description등을 설정한다.
  • Notification 표시 여부 설정.
    • DownloadManager.Request setNotificationVisibility (int visibility)
  • Notification 없이 다운로드 하기 위해서는 permission을 추가해야한다.
    • android.permission.DOWNLOAD_WITHOUT_NOTIFICATION

DownloadManager.Query

  • DownloadManager에 요청한 request에 대한 filter를 추가할 때 사용한다.
  • ID나 다운로드 상태를 통해 filter가 가능하다.
    • DownloadManager.Query setFilterById (long… ids)
    • DownloadManager.Query setFilterByStatus (int flags)

Example

package com.example.imagedownloader;

import java.io.FileNotFoundException;
import java.util.List;

import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener{
  private Button downloadButton;
  private EditText downloadUrl;
  private ImageView imgView;

  private long lastedId = -1;

  private DownloadManager downloadManager;
  private DownloadManager.Request downloadRequest;
  private Uri urlToDownload;

  private BroadcastReceiver completeReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
      DownloadManager.Query query = new DownloadManager.Query();
      query.setFilterById(lastedId);
      long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1L);

      if (id != lastedId) {
        Toast.makeText(context, "ID not match: " + id + " " + lastedId, Toast.LENGTH_LONG);
        return;
      }

      Cursor cursor = downloadManager.query(query);
      cursor.moveToFirst();

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

      Log.e("DOWNLOAD", "download receive:");
      Log.e("DOWNLOAD", "status: " + status);
      Log.e("DOWNLOAD", "reason: " + reason);

      if (status == DownloadManager.STATUS_SUCCESSFUL && reason == 0) {
        Uri uri = downloadManager.getUriForDownloadedFile(lastedId);
        Toast.makeText(context, "Download completed.\n" + uri.toString(), Toast.LENGTH_LONG).show();
        imgView.setImageURI(uri);
      }
      else {
        Toast.makeText(context, "Download Failed[id: " + lastedId + "], Reason: " + reason, Toast.LENGTH_LONG).show();
      }
    }
  };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        downloadUrl = (EditText) findViewById(R.id.downloadURL);
        downloadButton = (Button) findViewById(R.id.downloadButton);
        downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        imgView = (ImageView) findViewById(R.id.imageView);

        downloadButton.setOnClickListener(this);

        downloadUrl.setText("http://10.0.2.2/Android.jpg");
    }


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

    @Override
    public void onPause() {
      super.onPause();
      unregisterReceiver(completeReceiver);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


  @Override
  public void onClick(View v) {
    // TODO Auto-generated method stub
    urlToDownload = Uri.parse(downloadUrl.getText().toString());
    List pathSegments = urlToDownload.getPathSegments();

    downloadRequest = new DownloadManager.Request(urlToDownload);
    downloadRequest.setMimeType("Image");
    downloadRequest.setTitle("Image Downloader");
    downloadRequest.setDescription("Downloding a image...");
    downloadRequest.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, pathSegments.get(pathSegments.size() - 1));
    downloadRequest.addRequestHeader("Connection", "close");

    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdirs();
    lastedId = downloadManager.enqueue(downloadRequest);

    downloadUrl.setText("http://10.0.2.2/Android.jpg");
  }
}

댓글 없음:

댓글 쓰기