android 使用download Manager实现应用下载安装

        android 2.3中引入了download manager ,作为一个service来优化长时间下载操作处理。download manager通过处理http 连接、监听连续的变化和系统重新启动来确保每一次下载都能成功完成。

最好大多数场景下都使用download manager,特别是在一个下载可能会在多个用户回话之间在后台继续进行的地方或者在某个下载的完成非常重要的时候。

1、用到的权限

 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION"/>
2、实现现在文件,需要创建一个新的DownloadManager.Request,指定要下载的文件的uri

/**
     * 下载文件
     */
    private void Download(){
        
        String serviceString = Context.DOWNLOAD_SERVICE;
        downloadManager = (DownloadManager)getSystemService(serviceString);
        Uri uri = Uri.parse("http://dingphone.ufile.ucloud.com.cn/apk/guanwang/time2plato.apk");
        //Uri uri = Uri.parse("http://omoml61n3.bkt.clouddn.com/Android%E5%BA%94%E7%94%A8%E6%BA%90%E7%A0%81%E9%9F%B3%E4%B9%90%E5%AE%9E%E6%97%B6%E8%B7%B3%E5%8A%A8%E9%A2%91%E8%B0%B1%E6%98%BE%E7%A4%BA.rar");
        DownloadManager.Request request = new DownloadManager.Request(uri);

        //设置下载路径
        request.setDestinationInExternalPublicDir("download", "time2plato.apk");

        request.setTitle("标题");
        request.setDescription("文件下载名设置");

        //wifi才下载
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        request.setMimeType("application/vnd.android.package-archive");
        id = downloadManager.enqueue(request);

    }
3、想要在文件下载完成后对文件进行操作需要注册一个Receiver来接收 ACTION_DOWNLOAD_COMPLETE广播

IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                    Receive(intent);
                    openFile(new File("/sdcard/Download/time2plato.apk"));
                }else if (intent.getAction().equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)){
                    Toast.makeText(getApplication(),"正在下载",Toast.LENGTH_SHORT).show();
                }
            }
        };
        registerReceiver(receiver,filter);
4、下载完成后打开安装功能实现

/**
     * 跳转更新文件
     * @param file
     */
    private void openFile(File file) {

        // TODO Auto-generated method stub
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }
5、取消和删除下载,romove方法可以接受下载id作为参数选择,并且允许指定一个或多个要取消的下载。downloadManager.remove(id1,id2,id3);

downloadManager.remove(id);
6、获取下载文件名和路径实现

 /**
     * 获取文件下载路径和uri
     * @param intent
     */
    private void Receive(Intent intent){
        long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1);

        DownloadManager.Query mydown = new DownloadManager.Query();
        mydown.setFilterById(reference);
        Cursor myDownload = downloadManager.query(mydown);
        if (myDownload.moveToFirst()){
            int fileNameIdx = myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
            int fileUriIdx = myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
            String fileName = myDownload.getString(fileNameIdx);
            String fileUri = myDownload.getString(fileUriIdx);
            tvDown.setText("filename="+fileName+" fileUri="+fileUri);
        }
        myDownload.close();
    }

7、获取当前下载状态

/**
     * 获取当前状态
     */
    private void queryDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(id);
        Cursor c = downloadManager.query(query);
        if(c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch(status) {
                case DownloadManager.STATUS_PAUSED:
                    Log.e("down", "STATUS_PAUSED");
                case DownloadManager.STATUS_PENDING:
                    Log.e("down", "STATUS_PENDING");
                case DownloadManager.STATUS_RUNNING:
                    //正在下载,不做任何事情
                    Log.e("down", "STATUS_RUNNING");
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    //完成
                    Log.e("down", "下载完成");
                    break;
                case DownloadManager.STATUS_FAILED:
                    //清除已下载的内容,重新下载
                    Log.e("down", "STATUS_FAILED");
                    break;
            }
        }
    }

8、取消注册
 @Override
    protected void onDestroy() {
        if (receiver!=null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
        super.onDestroy();
    }
最后完整代码

package com.example.apple.downloadmanager;

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.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

public class MainActivity extends AppCompatActivity {

    private Button btnDown;
    private DownloadManager downloadManager;
    private BroadcastReceiver receiver;
    private TextView tvDown;
    private Button btnRemove;
    private long id;

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

        initView();
    }

    private void initView() {
        tvDown = (TextView)findViewById(R.id.tv_down);
        btnDown = (Button)findViewById(R.id.btn_down);
        btnDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Download();
                //intoDownloadManager();

            }
        });

        IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                    Receive(intent);
                    openFile(new File("/sdcard/Download/time2plato.apk"));
                }else if (intent.getAction().equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)){
                    Toast.makeText(getApplication(),"正在下载",Toast.LENGTH_SHORT).show();
                }
            }
        };
        registerReceiver(receiver,filter);

        btnRemove = (Button)findViewById(R.id.btn_remove);
        btnRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // downloadManager.remove(id);
                queryDownloadStatus();
            }
        });
    }

    /**
     * 获取当前状态
     */
    private void queryDownloadStatus() {
        DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(id);
        Cursor c = downloadManager.query(query);
        if(c.moveToFirst()) {
            int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
            switch(status) {
                case DownloadManager.STATUS_PAUSED:
                    Log.e("down", "STATUS_PAUSED");
                case DownloadManager.STATUS_PENDING:
                    Log.e("down", "STATUS_PENDING");
                case DownloadManager.STATUS_RUNNING:
                    //正在下载,不做任何事情
                    Log.e("down", "STATUS_RUNNING");
                    break;
                case DownloadManager.STATUS_SUCCESSFUL:
                    //完成
                    Log.e("down", "下载完成");
                    break;
                case DownloadManager.STATUS_FAILED:
                    //清除已下载的内容,重新下载
                    Log.e("down", "STATUS_FAILED");
                    break;
            }
        }
    }

    /**
     * 跳转更新文件
     * @param file
     */
    private void openFile(File file) {

        // TODO Auto-generated method stub
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }

    /**
     * 下载文件
     */
    private void Download(){

        String serviceString = Context.DOWNLOAD_SERVICE;
        downloadManager = (DownloadManager)getSystemService(serviceString);
        Uri uri = Uri.parse("http://dingphone.ufile.ucloud.com.cn/apk/guanwang/time2plato.apk");
        //Uri uri = Uri.parse("http://omoml61n3.bkt.clouddn.com/Android%E5%BA%94%E7%94%A8%E6%BA%90%E7%A0%81%E9%9F%B3%E4%B9%90%E5%AE%9E%E6%97%B6%E8%B7%B3%E5%8A%A8%E9%A2%91%E8%B0%B1%E6%98%BE%E7%A4%BA.rar");
        DownloadManager.Request request = new DownloadManager.Request(uri);

        //设置下载路径
        request.setDestinationInExternalPublicDir("download", "time2plato.apk");

        request.setTitle("标题");
        request.setDescription("文件下载名设置");

        //wifi才下载
        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        request.setMimeType("application/vnd.android.package-archive");
        id = downloadManager.enqueue(request);

    }

    /**
     * 获取文件下载路径和uri
     * @param intent
     */
    private void Receive(Intent intent){
        long reference = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID,-1);

        DownloadManager.Query mydown = new DownloadManager.Query();
        mydown.setFilterById(reference);
        Cursor myDownload = downloadManager.query(mydown);
        if (myDownload.moveToFirst()){
            int fileNameIdx = myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
            int fileUriIdx = myDownload.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
            String fileName = myDownload.getString(fileNameIdx);
            String fileUri = myDownload.getString(fileUriIdx);
            tvDown.setText("filename="+fileName+" fileUri="+fileUri);
        }
        myDownload.close();
    }

    @Override
    protected void onDestroy() {
        if (receiver!=null) {
            unregisterReceiver(receiver);
            receiver = null;
        }
        super.onDestroy();
    }
}
代码下载: http://download.csdn.net/detail/u011324501/9812299






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值