Android DownloadManager的使用

本文介绍了一个使用Android DownloadManager API实现的应用示例,演示如何开始、停止下载任务,查询下载状态,安装及打开下载的APK文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/downloadBtnBegin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="开始下载" />
    <Button
        android:id="@+id/downloadBtnStop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/downloadBtnBegin" 
        android:onClick="onClick"
        android:text="停止下载" />
    <Button
        android:id="@+id/downloadBtnLook"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/downloadBtnStop" 
        android:onClick="onClick"
        android:text="查看下载" />
    
    <Button
        android:id="@+id/downloadBtnInstall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/downloadBtnLook"
        android:onClick="onClick"
        android:text="安装下载apk"  />
    <Button
        android:id="@+id/downloadBtnOpen"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/downloadBtnInstall"
        android:onClick="onClick"
        android:text="打开apk"  />

</RelativeLayout>

Activity代码:

package com.cn.demoandroiddownloadmanager;

import java.io.File;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity{
	private String TAG = MainActivity.class.getSimpleName();
	private String urlString = "http://gdown.baidu.com/data/wisegame/b7d7e4efd8199dea/tianyiyuedu_310.apk";
	private DownloadManager downloadManager;
	long reference = 0L;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_main);

		downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
	}

	public void onClick(View view){
		int id = view.getId();
		switch (id) {
		case R.id.downloadBtnBegin:
			beginDownLoad();
			break;
		case R.id.downloadBtnStop:
			//注意参数可以是多个,也就是可以remove多个下载任务
			downloadManager.remove(reference);
			break;
		case R.id.downloadBtnLook:
			queryDownloadStatus(reference);
			break;
		case R.id.downloadBtnInstall:
			installApk();
			break;
		case R.id.downloadBtnOpen:
			openApk(urlString);
			break;
		}
	}
	
	private void openApk(String url) {
		PackageManager manager = getPackageManager();
        // 这里的是你下载好的文件路径
        PackageInfo info = manager.getPackageArchiveInfo(getFile(url).getPath(), PackageManager.GET_ACTIVITIES);
        if (info != null) {
            Intent intent = manager.getLaunchIntentForPackage(info.applicationInfo.packageName);
            startActivity(intent);
        }
        
	}

	/**
	 * 生成文件
	 * <p>{@link #getFileName(String)}</p>
	 * @param url
	 * @return
	 */
	private File getFile(String url) {
		File files = new File(Environment.getExternalStorageDirectory().getAbsoluteFile(), getFileName(url));
        return files;
	}
	
	/**
	 * 截取出url后面的apk的文件名
	 * @param url
	 * @return
	 */
	private String getFileName(String url) {
        return url.substring(url.lastIndexOf("/"), url.length());
    }

	protected void installApk() {
		String fileName = "";
		DownloadManager.Query query = new DownloadManager.Query();
		//设置过滤状态
		query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
		//查询以前下载过的“成功文件”
		Cursor c = downloadManager.query(query);
		if (c.moveToFirst()) {
			fileName = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
		}
		System.out.println("==============文件名============"+fileName);
		// TODO 下载完成后安装
		Intent intent = new Intent(Intent.ACTION_VIEW);
		File file = new File(fileName.replace("file://", ""));  //"/download/downtest.apk"
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		startActivity(intent);
	}

	/**
	 * {@link #beginDownLoad()}
	 * @throws IllegalAccessException
	 */
	@SuppressWarnings("unused")
	private void handleException() throws IllegalAccessException{
		throw new IllegalAccessException("ces");
	}
	
	@SuppressLint("NewApi")
	protected void beginDownLoad() {
		// 创建下载请求
		DownloadManager.Request down = new DownloadManager.Request(
				Uri.parse(urlString));
		// 设置允许使用的网络类型,这里是移动网络和wifi都可以
		down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
				| DownloadManager.Request.NETWORK_WIFI);
		//在通知栏中显示   
		down.setNotificationVisibility(View.VISIBLE);
		// 显示下载界面
		down.setVisibleInDownloadsUi(true);
		// 设置下载后文件存放的位置,该位置下只能使用root explore打开。
//		down.setDestinationInExternalFilesDir(MainActivity.this, null,"downtest.png");
		// sdcard的目录下的download文件夹
        down.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, getFileName(urlString));
        //在通知栏里显示
		down.setTitle("apk_title");
		down.setDescription("apk_description");
		//在这里返回的reference变量是系统为当前的下载请求分配的一个唯一的ID,
		//我们可以通过这个ID重新获得这个下载任务,进行一些自己想要进行的操作或者
		//查询下载的状态以及取消下载等等。
		reference = downloadManager.enqueue(down);
		// 将下载请求放入队列
		//queryDownloadStatus();
	}

	private void queryDownloadStatus(Long id) {   
        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.i(TAG, "STATUS_PAUSED");  
            case DownloadManager.STATUS_PENDING:   
                Log.i(TAG, "STATUS_PENDING");  
            case DownloadManager.STATUS_RUNNING:   
                //正在下载,不做任何事情  
                Log.i(TAG, "STATUS_RUNNING");  
                break;   
            case DownloadManager.STATUS_SUCCESSFUL:   
                //完成  
                Log.i(TAG, "下载完成");  
                break;   
            case DownloadManager.STATUS_FAILED:   
                //清除已下载的内容,重新下载  
                Log.i(TAG, "STATUS_FAILED");  
                downloadManager.remove(reference);   
                //该方法返回成功取消的下载的个数,
                //如果一个下载被取消了,所有相关联的文件,部分下载的文件和完全下载的文件都会被删除。
                break;   
            }   
        }  
    }  
	@Override
	protected void onResume() {
		super.onResume();
		registerReceiver(receiver, new IntentFilter(
				DownloadManager.ACTION_DOWNLOAD_COMPLETE));
	}

	public BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			long downId = intent.getLongExtra(
					DownloadManager.EXTRA_DOWNLOAD_ID, -1);
			if (intent.getAction().equals(
					DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
				Log.v(TAG, " download complete! id : " + downId);
				Toast.makeText(context, "下载完成==>"+"id : " + downId,
						Toast.LENGTH_SHORT).show();
			}

		}
	};
	
	protected void onDestroy() {
		if (receiver != null) {
			unregisterReceiver(receiver);
		}
		super.onDestroy();
	};
}

下载地址

点击打开链接

参考

http://www.it165.net/pro/html/201407/17644.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值