android网络编程之HttpUrlConnection的讲解--DownLoadManager基本用法

1、DownLoadManager是Android用系统服务(Service)的方式来优化处理长时间的下载操作的一个工具类。避免了我们去处理多线程,通知栏等等。

2、不要忘记添加权限

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

3、

public class MainActivity extends Activity {
    private DownloadManager downloadManager;
    
    private long downloadId;
    
    private TextView mTvMsg;
    
    private String downId;
    private String title;
    private String address;
    private String size;
    private String sizeTotal;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        initView();
        initData();
    }
    
    private void initView(){
        mTvMsg = (TextView) findViewById(R.id.tv_msg);
    }
    
    private void initData(){
        downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
        String apkUrl = "http://img.meilishuo.net/css/images/AndroidShare/Meilishuo_3.6.1_10006.apk";
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(apkUrl));
        
        // 设置下载地址为sd卡的Trinea文件夹,文件名为MeiLiShuo.apk
        request.setDestinationInExternalPublicDir("aaaa", "MeiLiShuo.apk");
        
        // 表示允许MediaScanner扫描到这个文件,默认不允许
        request.allowScanningByMediaScanner();
        
        // 设置下载中通知栏提示的标题
        request.setTitle("MeiLiShuo");
        
        // 设置下载中通知栏提示的介绍
        request.setDescription("美丽说");
        
        // 默认只显示下载中通知。VISIBILITY_VISIBLE_NOTIFY_COMPLETED表示下载完成后显示通知栏提示。VISIBILITY_HIDDEN表示不显示任何通知栏提示,
        // 这个需要在AndroidMainfest中添加权限android.permission.DOWNLOAD_WITHOUT_NOTIFICATION
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
        
        // 设置下载文件的mineType。因为下载管理Ui中点击某个已下载完成文件及下载完成点击通知栏提示都会根据mimeType去打开文件,
        // 所以我们可以利用这个属性用于响应点击的打开文件
        request.setMimeType("application/cn.trinea.download.file");
        
        // 添加请求下载的网络链接的http头,比如User-Agent,gzip压缩等
        // request.addRequestHeader(String header, String value)
        
        downloadId = downloadManager.enqueue(request);
        
        new Thread(thread).start();
    }

    /** 查询下载任务信息*/
    private void queryDownTask(DownloadManager downManager,long id) {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(id);
        Cursor cursor= downManager.query(query);
 
        while(cursor.moveToNext()){
            downId= cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
            title = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE));
            address = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
            //String statuss = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
            size= cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
            sizeTotal = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
        }
        cursor.close();
    }
    
    private Thread thread = new Thread(){
        public void run() {
            while (true) {
                queryDownTask(downloadManager, downloadId);
                
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                
                handler.sendEmptyMessage(0);
            }
        };
    };
    
    private Handler handler = new Handler(){
        public void handleMessage(android.os.Message msg) {
            if(msg.what == 0){
                mTvMsg.setText(downId + "\n" + title + "\n" + address + "\n" + size + "\n" + sizeTotal);
            }
        };
    };
}

4、下载成功后系统会发出广播DownloadManager.ACTION_DOWNLOAD_COMPLETE,并传递并传递downloadId作为参数。我们可以监听广播来进行下载后的操作。

<!-- 注册系统静态广播接收器 -->  
        <receiver android:name=".DownloadReceive">  
            <intent-filter>  
                <action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
            </intent-filter>  
        </receiver>
public class DownloadReceive extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); 
        
        Toast.makeText(context, reference + "", Toast.LENGTH_SHORT).show();
    }

}

5、有了通知栏其实下载进度可以不用监听的,不过我们还是可以通过DownManager.Query和Cursor查询下载信息。

6、参考博文:http://www.open-open.com/lib/view/open1428024407365.html

posted on 2015-12-30 09:44  StephenHe  阅读(1320)  评论(0编辑  收藏  举报

导航