Android - Download(下载) 项目 详解

Download(下载) 项目 详解


本文地址: http://blog.csdn.net/caroline_wendy/article/details/22280461


本文的合集已经编著成书,《高级Android开发强化实战》,欢迎各位读友的建议和指导。

在京东即可购买:https://item.jd.com/12385680.html





环境: Android 0.5.2 + gradle 1.11 + kindle fire

Download, 下载项目, 从Internet上下载资源, 并存入本地SD卡.

点击Download按钮, 下载图片, 然后显示下载内容, 可以点击查看.


Download的具体设计:

1. 修改activity_main.xml

位置: res->layout->activity_main.xml

<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"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="mzx.spike.download.app.MainActivity">

    <Button
        android:id="@+id/download_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download"/>

    <TextView
        android:text="@string/hello_world"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/download_button" />

</RelativeLayout>

添加一个 按钮(Button) , 使"hello_world"在其下方, 使用 layout_below 属性;


2. 修改AndroidManifest.xml

位置: main->AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="mzx.spike.download.app" >

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="mzx.spike.download.app.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

需要INTERNET, 连接互联网的权限; WRITE_EXTERNAL_STORAGE, 写入存储器的权限;


3. 修改MainActivity.java

位置: java->package->MainActivity.java

package mzx.spike.download.app;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


public class MainActivity extends Activity {

    private static final String TAG = "Download";

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

        Button buttonDownload = (Button)findViewById(R.id.download_button);
        buttonDownload.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                myDownload();
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void myDownload() {

        String serviceString = Context.DOWNLOAD_SERVICE;
        DownloadManager downloadManager;
        downloadManager = (DownloadManager) getSystemService(serviceString);

        Uri uri = Uri.parse("http://bizhi.zhuoku.com/2014/03/26/TAHITI/TAHITI02.jpg");
        DownloadManager.Request request = new DownloadManager.Request(uri);

        request.setDestinationInExternalPublicDir("/Download", "file.jpg");
        request.setVisibleInDownloadsUi(true);
        long reference = downloadManager.enqueue(request);

        Log.d(TAG, "Download Reference: " + reference);

        Cursor c = downloadManager.query(new DownloadManager.Query().setFilterById(reference));
        if (c == null) {
            Toast.makeText(this, "Download not found!", Toast.LENGTH_LONG).show();
        } else {
            c.moveToFirst();
            Log.d(getClass().getName(), "Column_id : " +
                    c.getLong(c.getColumnIndex(DownloadManager.COLUMN_ID)));
            Log.d(getClass().getName(), "Column_bytes_downloaded so far : " +
                    c.getLong(c.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)));
            Log.d(getClass().getName(), "Column last modified timestamp : " +
                    c.getLong(c.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP)));
            Log.d(getClass().getName(), "Column local uri : " +
                    c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)));
            Log.d(getClass().getName(), "Column statue : " +
                    c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS)));
            Log.d(getClass().getName(), "Column reason : " +
                    c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON)));

            Toast.makeText(this, statusMessage(c), Toast.LENGTH_LONG).show();
        }

        startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));
    }


    private String statusMessage(Cursor c){
        switch(c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS))){
            case DownloadManager.STATUS_FAILED:
                return "Download failed";
            case DownloadManager.STATUS_PAUSED:
                return "Download paused";
            case DownloadManager.STATUS_PENDING:
                return "Download pending";
            case DownloadManager.STATUS_RUNNING:
                return "Download in progress!";
            case DownloadManager.STATUS_SUCCESSFUL:
                return "Download finished";
            default:
                return "Unknown Information";
        }
    }

}

详解:

1. 在创建界面中, 填写按钮(button)点击事件(setOnClickListener), 触发下载方法(myDownload);

2. DownloadManager 获取下载的服务(Context.DOWNLOAD_SERVICE);

3. 设置下载的链接(uri), 设置存储位置(setDestinationInExternalPublicDir), 显示下载用户接口(setVisibleInDownloadsUi);

4. 放置下载队列, 开始下载, downloadManager.enqueue(request);

5. 通过游标获取下载信息, downloadManager.query();

6. 输出相应的下载信息(COLUMN_*), 和下载状态(STATUS_*);

7. 显示下载视图(DownloadManager.ACTION_VIEW_DOWNLOADS);

注意: 

存储位置(setDestinationInExternalPublicDir), 需要提前设置, 否则无法查看文件, 存储至content位置;


4. 运行程序


下载地址: http://download.csdn.net/detail/u012515223/7106567


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ElminsterAumar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值