說(shuō)說(shuō)如何使用 Android 服務(wù)下載文件(支持?jǐn)帱c(diǎn)續(xù)傳)

1 添加網(wǎng)絡(luò)庫(kù)

在 build.gradle 中添加 okhttp3 庫(kù):

compile 'com.squareup.okhttp3:okhttp:3.10.0'

2 定義監(jiān)聽(tīng)器

定義下載監(jiān)聽(tīng)器,監(jiān)聽(tīng)下載過(guò)程中的各種情況:

public interface DownloadListener {

    /**
     * 當(dāng)前下載進(jìn)度
     *
     * @param progress 下載進(jìn)度
     */
    void onProgress(int progress);

    /**
     * 下載成功
     */
    void onSuccess();

    /**
     * 下載失敗
     */
    void onFailed();

    /**
     * 暫停下載
     */
    void onPaused();

    /**
     * 取消下載
     */
    void onCanceled();
}

3 定義異步下載任務(wù)

public class DownloadTask extends AsyncTask<String, Integer, DownloadTask.DownloadResult> {


    private static final String TAG = "DownloadTask";

    /**
     * 下載結(jié)果
     */
    public enum DownloadResult {
        //下載成功
        SUCCESS,
        //下載失敗
        FAILED,
        //下載被暫停
        PAUSED,
        //下載被取消
        CANCELED
    }

    //是否取消下載
    private boolean isCanceled = false;

    //是否暫停下載
    private boolean isPaused = false;

    //上一次的下載進(jìn)度
    private int lastProgress;


    private DownloadListener listener;


    public DownloadTask(DownloadListener listener) {
        this.listener = listener;
    }

    /**
     * 下載
     *
     * @param params
     * @return
     */
    @Override
    protected DownloadResult doInBackground(String... params) {
        InputStream inputStream = null;
        RandomAccessFile downloadedFile = null;
        File file = null;

        try {
            long downloadedLength = 0;//文件已下載的大小
            String url = params[0];//獲取下載地址
            String fileName = url.substring(url.lastIndexOf("/"));
            //指定 SD 卡的 Download 目錄
            String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
            file = new File(directory + fileName);

            if (file.exists()) {//文件已存在,則讀取已下載的文件字節(jié)數(shù)(用于斷點(diǎn)續(xù)傳)
                downloadedLength = file.length();
            }

            long contentLength = getContentLength(url);//獲取待下載文件的總長(zhǎng)度
            Log.d(TAG, "doInBackground: 待下載文件的總長(zhǎng)度:" + contentLength);
            Log.d(TAG, "doInBackground: 已下載文件的總長(zhǎng)度:" + downloadedLength);
            if (contentLength == 0) {//下載失敗
                return DownloadResult.FAILED;
            } else if (contentLength == downloadedLength) {//下載成功
                return DownloadResult.SUCCESS;
            }

            OkHttpClient client = buildHttpClient();
            Request request = new Request.Builder()
                    //指定從那個(gè)字節(jié)開(kāi)始下載,即【斷點(diǎn)下載】
                    .addHeader("RANGE", "bytes=" + downloadedLength + "-")
                    .url(url)
                    .build();
            Response response = client.newCall(request).execute();
            if (response != null) {
                inputStream = response.body().byteStream();
                downloadedFile = new RandomAccessFile(file, "rw");
                downloadedFile.seek(downloadedLength);//跳轉(zhuǎn)到未下載的字節(jié)節(jié)點(diǎn)
                byte[] bytes = new byte[1024];
                int total = 0;//下載的總字節(jié)數(shù)
                int readLength;//讀取的字節(jié)數(shù)
                while ((readLength = inputStream.read(bytes)) != -1) {
                    //在下載的過(guò)程中,判斷下載是否被取消或者被暫停
                    if (isCanceled) {//取消
                        return DownloadResult.CANCELED;
                    } else if (isPaused) {//暫停
                        return DownloadResult.PAUSED;
                    } else {
                        total += readLength;
                        downloadedFile.write(bytes, 0, readLength);
                        //計(jì)算已下載的進(jìn)度(單位:百分比)
                        int progress = (int) ((total + downloadedLength) * 100 / contentLength);
                        //發(fā)布下載進(jìn)度
                        publishProgress(progress);
                    }
                }
                response.body().close();
                return DownloadResult.SUCCESS;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (downloadedFile != null) {
                    downloadedFile.close();
                }
                if (isCanceled && file != null) {
                    file.delete();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return DownloadResult.FAILED;
    }

    @NonNull
    private OkHttpClient buildHttpClient() {
        return new OkHttpClient.Builder().retryOnConnectionFailure(true).connectTimeout(30, TimeUnit.SECONDS).build();
    }

    /**
     * 更新當(dāng)前的下載進(jìn)度
     *
     * @param values
     */
    @Override
    protected void onProgressUpdate(Integer... values) {
        int progress = values[0];
        if (progress > lastProgress) {
            listener.onProgress(progress);
            lastProgress = progress;
        }
    }

    /**
     * 根據(jù)下載結(jié)果調(diào)用相應(yīng)的回調(diào)方法
     *
     * @param result
     */
    @Override
    protected void onPostExecute(DownloadResult result) {
        switch (result) {
            case SUCCESS:
                listener.onSuccess();
                break;
            case FAILED:
                listener.onFailed();
                break;
            case PAUSED:
                listener.onPaused();
                break;
            case CANCELED:
                listener.onCanceled();
                break;
            default:
                break;
        }
    }

    /**
     * 暫停下載
     */
    public void pause() {
        isPaused = true;
    }

    /**
     * 取消下載
     */
    public void cancel() {
        isCanceled = true;
    }


    /**
     * 獲取待下載文件的總長(zhǎng)度
     *
     * @param url 下載文件地址
     * @return
     */
    private long getContentLength(String url) throws IOException {
        Log.d(TAG, "getContentLength:url:" + url);
        OkHttpClient client = buildHttpClient();
        Request request = new Request.Builder().url(url).build();
        Response response = client.newCall(request).execute();
        if (response != null && response.isSuccessful()) {
            long contentLength = response.body().contentLength();
            response.close();
            return contentLength;
        } else {
            return 0;
        }
    }


}

DownloadTask 類(lèi)做了這些工作:

1、繼承 AsyncTask 類(lèi)并傳入三個(gè)參數(shù):

extends AsyncTask<String, Integer, DownloadTask.DownloadResult>
參數(shù) 說(shuō)明
String 表示傳遞到后臺(tái)服務(wù)的參數(shù)類(lèi)型,這里參數(shù)指的是文件下載 URL 地址。
Integer 表示使用整型數(shù)據(jù)作為下載進(jìn)度的顯示單位。
DownloadResult 使用 DownloadResult 枚舉類(lèi)型來(lái)定義下載結(jié)果。

2、定義了枚舉類(lèi)型的下載結(jié)果。
3、重寫(xiě)了這些方法:

  • doInBackground - 執(zhí)行下載操作。
  • onProgressUpdate - 更新當(dāng)前的下載進(jìn)度。
  • onPostExecute - 根據(jù)下載結(jié)果調(diào)用相應(yīng)的回調(diào)方法。

在 doInBackground 中,根據(jù)已下載的文件字節(jié)總數(shù)與要下載的字節(jié)總數(shù)做比較,讓程序直接跳過(guò)已下載的字節(jié),所以支持?jǐn)帱c(diǎn)續(xù)傳哦O(∩_∩)O哈哈~

4 定義下載服務(wù)

public class DownloadService extends Service {

    private DownloadTask task;

    private String url;

    public static final int NOTIFICATION_ID = 1;


    private DownloadListener listener = new DownloadListener() {
        @Override
        public void onProgress(int progress) {
            getNotificationManager().notify(NOTIFICATION_ID, buildNotification("下載中……", progress));
        }

        @Override
        public void onSuccess() {
            task = null;

            //關(guān)閉前臺(tái)服務(wù)
            stopForeground(true);

            //通知下載成功
            getNotificationManager().notify(NOTIFICATION_ID, buildNotification("下載成功", -1));
            Toast.makeText(DownloadService.this, "下載成功", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailed() {
            task = null;

            //關(guān)閉前臺(tái)服務(wù)
            stopForeground(true);

            //通知下載失敗
            getNotificationManager().notify(NOTIFICATION_ID, buildNotification("下載失敗", -1));
            Toast.makeText(DownloadService.this, "下載失敗", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onPaused() {
            task = null;
            Toast.makeText(DownloadService.this, "暫停下載", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCanceled() {
            task = null;

            //關(guān)閉前臺(tái)服務(wù)
            stopForeground(true);

            //通知下載取消
            Toast.makeText(DownloadService.this, "取消下載", Toast.LENGTH_SHORT).show();
        }
    };


    private NotificationManager getNotificationManager() {
        return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }


    /**
     * 構(gòu)建【下載進(jìn)度】通知
     *
     * @param title    通知標(biāo)題
     * @param progress 下載進(jìn)度
     */
    private Notification buildNotification(String title, int progress) {
        Intent intent = new Intent(this, MainActivity.class);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setContentTitle(title);
        int requestCode = 0;
        int flags = PendingIntent.FLAG_UPDATE_CURRENT;
        builder.setContentIntent(PendingIntent.getActivity(this, requestCode, intent, flags));
        if (progress > 0) {
            builder.setContentText(progress + "%");
            builder.setProgress(100, progress, false);
        }
        return builder.build();
    }

    public DownloadService() {
    }


    @Override
    public IBinder onBind(Intent intent) {
        return new DownloadBinder();
    }

    /**
     * 通過(guò) Binder 讓服務(wù)與活動(dòng)之間實(shí)現(xiàn)通信
     */
    protected class DownloadBinder extends Binder {
        /**
         * 開(kāi)始下載
         *
         * @param url
         */
        public void start(String url) {
            if (task == null) {
                DownloadService.this.url = url;
                task = new DownloadTask(listener);
                task.execute(url);
                startForeground(NOTIFICATION_ID, buildNotification("開(kāi)始下載……", 0));
                Toast.makeText(DownloadService.this, "開(kāi)始下載……", Toast.LENGTH_SHORT).show();
            }
        }

        /**
         * 暫停下載
         */
        public void pause() {
            if (task != null) {
                task.pause();
            }
        }

        /**
         * 取消下載
         */
        public void cancel() {
            if (task != null) {
                task.cancel();
                return;
            }

            if (url == null) {
                return;
            }

            //刪除已下載文件
            String fileName = url.substring(url.lastIndexOf("/"));
            String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
            File file = new File(directory + fileName);
            if (file.exists()) {
                file.delete();
            }

            //關(guān)閉通知
            getNotificationManager().cancel(NOTIFICATION_ID);
            stopForeground(true);
            Toast.makeText(DownloadService.this, "被取消", Toast.LENGTH_SHORT).show();

        }
    }
}

這個(gè)大類(lèi)做了以下工作:

  1. 通過(guò)匿名類(lèi)創(chuàng)建了 DownloadListener 實(shí)例。
  2. 構(gòu)建【下載進(jìn)度】通知。
  3. 通過(guò) Binder 讓服務(wù)與活動(dòng)之間實(shí)現(xiàn)通信。

這里的 setProgress 定義如下:

public Builder setProgress(int max, int progress, boolean indeterminate)
參數(shù) 說(shuō)明
max 最大進(jìn)度。
progress 當(dāng)前進(jìn)度。
indeterminate 是否使用模糊進(jìn)度條。

5 定義控制按鈕

布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/start"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="開(kāi)始下載" />

    <Button
        android:id="@+id/pause"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="暫停下載" />

    <Button
        android:id="@+id/cancel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="取消下載" />


</LinearLayout>

這里,我們定義了【開(kāi)始】、【暫?!颗c【取消】按鈕。

6 定義活動(dòng)類(lèi)

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public static final int REQUEST_CODE = 1;


    private DownloadService.DownloadBinder binder;

    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            binder = (DownloadService.DownloadBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

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

        findViewById(R.id.start).setOnClickListener(this);
        findViewById(R.id.pause).setOnClickListener(this);
        findViewById(R.id.cancel).setOnClickListener(this);

        Intent intent = new Intent(this, DownloadService.class);

        //啟動(dòng)服務(wù),讓【下載】服務(wù)持續(xù)在后臺(tái)運(yùn)行
        startService(intent);

        //綁定服務(wù),讓活動(dòng)與服務(wù)之間實(shí)現(xiàn)通信
        bindService(intent, connection, BIND_AUTO_CREATE);

        //申請(qǐng)權(quán)限
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_CODE);
        }
    }

    @Override
    public void onClick(View v) {
        if (binder == null) {
            return;
        }

        switch (v.getId()) {
            case R.id.start:
                String url = "http://mirrors.shu.edu.cn/apache/maven/maven-3/3.5.4/binaries/apache-maven-3.5.4-bin.zip";
                binder.start(url);
                break;
            case R.id.pause:
                binder.pause();
                break;
            case R.id.cancel:
                binder.cancel();
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "權(quán)限被拒絕啦", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //解綁服務(wù)
        unbindService(connection);
    }
}

活動(dòng)類(lèi)中做了這些事:

  1. 建立與服務(wù)的綁定關(guān)系。
  2. 為按鈕定義點(diǎn)擊事件。
  3. 申請(qǐng)權(quán)限。

注意: 在 onDestroy() 中要記得解綁服務(wù)哦。

在代碼中,我們把 Maven 作為下載演示路徑。O(∩_∩)O哈哈~

7 聲明權(quán)限與服務(wù)

AndroidManifest.xml

<!--網(wǎng)絡(luò)權(quán)限-->
<uses-permission android:name="android.permission.INTERNET"/>

<!--訪問(wèn) SD 卡權(quán)限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

    <service
        android:name=".DownloadService"
        android:enabled="true"
        android:exported="true"></service>
</application>

8 運(yùn)行

第一次運(yùn)行會(huì)彈出權(quán)限申請(qǐng):

點(diǎn)擊 ALLOW 后,就可以點(diǎn)擊相應(yīng)的按鈕進(jìn)行下載控制啦。點(diǎn)擊【開(kāi)始】按鈕后,可以在通知中看到下載進(jìn)度:


一個(gè)支持?jǐn)帱c(diǎn)續(xù)傳的 Android 下載服務(wù)就完成啦,是不是很有成就感呀O(∩_∩)O哈哈~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 178,781評(píng)論 25 709
  • 下雨的時(shí)候生意很淡,來(lái)的人很少,她與她一起當(dāng)迎賓的那個(gè)女子,站在門(mén)口。沒(méi)有太多的話(huà)。青紅記得那個(gè)女子有個(gè)手機(jī),總是...
    無(wú)戒閱讀 1,972評(píng)論 6 19
  • 2018.6.25.星期一,雨 老公很早就上班去了,六點(diǎn)多點(diǎn)就聽(tīng)見(jiàn)大寶在屋里早讀,我醒了也不想起來(lái),感覺(jué)渾身像散了...
    三年級(jí)四班李雨軒媽媽閱讀 179評(píng)論 0 1
  • 老媽身體不舒服,所以今天帶老人家去醫(yī)院做檢查,雖然是正月里,但是醫(yī)院里人一點(diǎn)也不少,排隊(duì)掛號(hào)看病的人很多,醫(yī)生給老...
    Tracy_zhang閱讀 178評(píng)論 0 0

友情鏈接更多精彩內(nèi)容