android使用dowanloadmanager下載東西,並且擷取下載進度。

來源:互聯網
上載者:User

   package com.koolsee.gallery;   import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask;   import android.app.Activity; import android.app.DownloadManager; import android.app.DownloadManager.Request; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnKeyListener; import android.view.View.OnTouchListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView;     import com.koolsee.gallery.adapter.RecommendAdapter; import com.koolsee.gallery.model.Recommend; import com.koolsee.gallery.widget.GalleryFlow;   /** * 首頁 *  * @author zengxiaotao */ public class testActivity extends Activity {       private DownloadManager dowanloadmanager = null;     private DownloadChangeObserver downloadObserver;     private long lastDownloadId = 0;     public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");     @Override     protected void onCreate(Bundle savedInstanceState) {         // TODO Auto-generated method stub          super.onCreate(savedInstanceState);         setContentView(R.layout.test);         String serviceString = Context.DOWNLOAD_SERVICE;         dowanloadmanager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);           Uri uri = Uri.parse("http://commonsware.com/misc/test.mp4");         Environment.getExternalStoragePublicDirectory(                 Environment.DIRECTORY_DOWNLOADS).mkdir();           lastDownloadId = dowanloadmanager.enqueue(new DownloadManager.Request(uri)                 .setAllowedNetworkTypes(                         DownloadManager.Request.NETWORK_MOBILE                                 | DownloadManager.Request.NETWORK_WIFI)                 .setAllowedOverRoaming(false)                 .setDestinationInExternalPublicDir(                         Environment.DIRECTORY_DOWNLOADS, "test.mp4"));          registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));              downloadObserver = new DownloadChangeObserver(null);                 getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);     }     class DownloadChangeObserver extends ContentObserver {                public DownloadChangeObserver(Handler handler) {             super(handler);             // TODO Auto-generated constructor stub          }           @Override         public void onChange(boolean selfChange) {               queryDownloadStatus();            }       }      private BroadcastReceiver receiver = new BroadcastReceiver() {                @Override                public void onReceive(Context context, Intent intent) {                    //這裡可以取得下載的id,這樣就可以知道哪個檔案下載完成了。適用與多個下載任務的監聽                    Log.v("tag", ""+intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0));                   queryDownloadStatus();                }            };                     private void queryDownloadStatus() {                DownloadManager.Query query = new DownloadManager.Query();                query.setFilterById(lastDownloadId);                Cursor c = dowanloadmanager.query(query);                if(c!=null&&c.moveToFirst()) {                    int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));                                     int reasonIdx = c.getColumnIndex(DownloadManager.COLUMN_REASON);                   int titleIdx = c.getColumnIndex(DownloadManager.COLUMN_TITLE);                   int fileSizeIdx =                      c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);                       int bytesDLIdx =                      c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);                   String title = c.getString(titleIdx);                   int fileSize = c.getInt(fileSizeIdx);                   int bytesDL = c.getInt(bytesDLIdx);                                    // Translate the pause reason to friendly text.                    int reason = c.getInt(reasonIdx);                   StringBuilder sb = new StringBuilder();                   sb.append(title).append("\n");                  sb.append("Downloaded ").append(bytesDL).append(" / " ).append(fileSize);                                    // Display the status                     Log.d("tag", sb.toString());                   switch(status) {                    case DownloadManager.STATUS_PAUSED:                        Log.v("tag", "STATUS_PAUSED");                   case DownloadManager.STATUS_PENDING:                        Log.v("tag", "STATUS_PENDING");                   case DownloadManager.STATUS_RUNNING:                        //正在下載,不做任何事情                        Log.v("tag", "STATUS_RUNNING");                                                   break;                    case DownloadManager.STATUS_SUCCESSFUL:                        //完成                        Log.v("tag", "下載完成");   //                  dowanloadmanager.remove(lastDownloadId);                         break;                    case DownloadManager.STATUS_FAILED:                        //清除已下載的內容,重新下載                        Log.v("tag", "STATUS_FAILED");                       dowanloadmanager.remove(lastDownloadId);                        break;                    }                }           }                    @Override         protected void onDestroy() {             // TODO Auto-generated method stub              super.onDestroy();               unregisterReceiver(receiver);                 getContentResolver().unregisterContentObserver(downloadObserver);         } } package com.koolsee.gallery;import java.util.ArrayList;import java.util.List;import java.util.Timer;import java.util.TimerTask;import android.app.Activity;import android.app.DownloadManager;import android.app.DownloadManager.Request;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.database.ContentObserver;import android.database.Cursor;import android.net.Uri;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.util.Log;import android.view.KeyEvent;import android.view.MotionEvent;import android.view.View;import android.view.View.OnKeyListener;import android.view.View.OnTouchListener;import android.widget.AdapterView;import android.widget.AdapterView.OnItemClickListener;import android.widget.AdapterView.OnItemSelectedListener;import android.widget.Button;import android.widget.ImageView;import android.widget.TextView; import com.koolsee.gallery.adapter.RecommendAdapter;import com.koolsee.gallery.model.Recommend;import com.koolsee.gallery.widget.GalleryFlow;/** * 首頁 * * @author zengxiaotao */public class testActivity extends Activity { private DownloadManager dowanloadmanager = null;    private DownloadChangeObserver downloadObserver; private long lastDownloadId = 0;    public static final Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads"); @Override protected void onCreate(Bundle savedInstanceState) {  // TODO Auto-generated method stub  super.onCreate(savedInstanceState);  setContentView(R.layout.test);  String serviceString = Context.DOWNLOAD_SERVICE;  dowanloadmanager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);  Uri uri = Uri.parse("http://commonsware.com/misc/test.mp4");  Environment.getExternalStoragePublicDirectory(    Environment.DIRECTORY_DOWNLOADS).mkdir();  lastDownloadId = dowanloadmanager.enqueue(new DownloadManager.Request(uri)    .setAllowedNetworkTypes(      DownloadManager.Request.NETWORK_MOBILE        | DownloadManager.Request.NETWORK_WIFI)    .setAllowedOverRoaming(false)    .setDestinationInExternalPublicDir(      Environment.DIRECTORY_DOWNLOADS, "test.mp4"));   registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));         downloadObserver = new DownloadChangeObserver(null);          getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver); }    class DownloadChangeObserver extends ContentObserver {         public DownloadChangeObserver(Handler handler) {   super(handler);   // TODO Auto-generated constructor stub  }  @Override        public void onChange(boolean selfChange) {           queryDownloadStatus();          }    }  private BroadcastReceiver receiver = new BroadcastReceiver() {           @Override           public void onReceive(Context context, Intent intent) {               //這裡可以取得下載的id,這樣就可以知道哪個檔案下載完成了。適用與多個下載任務的監聽              Log.v("tag", ""+intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0));              queryDownloadStatus();           }       };           private void queryDownloadStatus() {           DownloadManager.Query query = new DownloadManager.Query();           query.setFilterById(lastDownloadId);           Cursor c = dowanloadmanager.query(query);           if(c!=null&&c.moveToFirst()) {               int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));                           int reasonIdx = c.getColumnIndex(DownloadManager.COLUMN_REASON);              int titleIdx = c.getColumnIndex(DownloadManager.COLUMN_TITLE);              int fileSizeIdx =                 c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);                  int bytesDLIdx =                 c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);              String title = c.getString(titleIdx);              int fileSize = c.getInt(fileSizeIdx);              int bytesDL = c.getInt(bytesDLIdx);                          // Translate the pause reason to friendly text.              int reason = c.getInt(reasonIdx);              StringBuilder sb = new StringBuilder();              sb.append(title).append("\n");             sb.append("Downloaded ").append(bytesDL).append(" / " ).append(fileSize);                          // Display the status               Log.d("tag", sb.toString());              switch(status) {               case DownloadManager.STATUS_PAUSED:                   Log.v("tag", "STATUS_PAUSED");              case DownloadManager.STATUS_PENDING:                   Log.v("tag", "STATUS_PENDING");              case DownloadManager.STATUS_RUNNING:                   //正在下載,不做任何事情                  Log.v("tag", "STATUS_RUNNING");                                 break;               case DownloadManager.STATUS_SUCCESSFUL:                   //完成                  Log.v("tag", "下載完成"); //                 dowanloadmanager.remove(lastDownloadId);                   break;               case DownloadManager.STATUS_FAILED:                   //清除已下載的內容,重新下載                  Log.v("tag", "STATUS_FAILED");                  dowanloadmanager.remove(lastDownloadId);                   break;               }           }      }          @Override     protected void onDestroy() {      // TODO Auto-generated method stub      super.onDestroy();        unregisterReceiver(receiver);         getContentResolver().unregisterContentObserver(downloadObserver);     }} 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.