2013年3月19日 星期二

DownloadManager


目的
使用DownloadManager下載檔案,並取出下載進度

問題

  1. permission denial
    解:
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  2. 使用 DownloadManager.Request.VISIBILITY_HIDDEN 時,發生SecurityException
    解:
    加入<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />


實作
public class DownloadActivity extends Activity {

 private TextView mConsole;

 private void setupUnit() {
  mConsole = (TextView) findViewById(R.id.console);
 }

 private void init() {

 }

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_download);

  setupUnit();
  init();

  Downloader d = new Downloader();
  d.download(this, "http://www.wall001.com/1280x1024/"
    + "1280_1024_nature_scene_wallpapers_06/"
    + "mxxx01/1280_1024_nature_wallpaper_3210710877.jpg");
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.activity_download, menu);
  return true;
 }

 private Handler mHander = new Handler() {
  public void handleMessage(Message msg) {
   String log = (String) msg.obj;

   mConsole.append(log);
  }
 };

 private class Downloader {
  
  DownloadManager downloadManager;
  long downloadId;
  boolean is = true;
  Cursor c;

  public void download(Context context, String url) {
   
   downloadManager = (DownloadManager) context
     .getSystemService(Context.DOWNLOAD_SERVICE);
   Uri uri = Uri.parse(url);

   downloadId= downloadManager.enqueue(new DownloadManager.Request(
     uri)
     .setAllowedNetworkTypes(
       DownloadManager.Request.NETWORK_WIFI |  
       DownloadManager.Request.NETWORK_MOBILE)
     .setAllowedOverRoaming(false)
     .setNotificationVisibility(
       DownloadManager.Request.VISIBILITY_HIDDEN)
     .setDestinationInExternalPublicDir(
       Environment.DIRECTORY_DOWNLOADS, "test.jpg"));

   final Query query = new DownloadManager.Query();   
   query.setFilterById(downloadId);

   // 取出下載進度
   new Thread(new Runnable() {
    
    long size = 0;
    long total = 0;

    @Override
    public void run() {
     
     while (is) {
      c = downloadManager.query(query);
      if (c != null) {
       if (c.moveToFirst()) {
        size = c.getInt(c
          .getColumnIndex(
              downloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
        total = c.getLong(c
          .getColumnIndex(downloadManager.COLUMN_TOTAL_SIZE_BYTES));

        mHander.sendMessage(mHander.obtainMessage(-1,
          "Progress- " + size + " / " + total
            + "\n"));

        if (size == total)
         is = false;
       }
      }

      try {
       Thread.sleep(500);
      } catch (InterruptedException e) {
       e.printStackTrace();
      }
     }
    }
   }).start();
  }
 }
}

沒有留言:

張貼留言