안 드 로 이 드 가 OKHttp 3 를 사용 하여 다운 로드 를 실현 하 는 것 을 자세히 설명 합 니 다(정지점 전송,진도 표시)

30698 단어 okhttp정지점 전송
OKHttp 3 는 현재 매우 유행 하 는 안 드 로 이 드 네트워크 요청 프레임 워 크 입 니 다.그러면 어떻게 안 드 로 이 드 를 이용 하여 정지점 전송 을 실현 할 수 있 습 니까?오늘 은 Demo 를 써 서 시도 해 보 았 는데 아직도 재 미 있 는 것 같 습 니 다.
준비 단계
우 리 는 OKHttp 3 를 사용 하여 네트워크 요청 을 할 것 입 니 다.RxJava 를 사용 하여 스 레 드 전환 을 실현 하고 자바 8 을 켜 서 Lambda 표현 식 을 사용 할 것 입 니 다.왜냐하면 RxJava 는 스 레 드 전환 을 실현 하 는 것 이 매우 편리 하고 데이터 흐름 의 형식 도 매우 편안 하 며 Lambda 와 RxJava 가 함께 먹 으 면 맛 이 더욱 좋 습 니 다.
app Module 의 build.gradle 을 엽 니 다.코드 는 다음 과 같 습 니 다.

apply plugin: 'com.android.application' 
 
android { 
  compileSdkVersion 24 
  buildToolsVersion "24.0.3" 
 
  defaultConfig { 
    applicationId "com.lanou3g.downdemo" 
    minSdkVersion 15 
    targetSdkVersion 24 
    versionCode 1 
    versionName "1.0" 
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 
    //    Java8 
    jackOptions{ 
      enabled true; 
    } 
  } 
  buildTypes { 
    release { 
      minifyEnabled false 
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 
    } 
  } 
 
  //  Java1.8     lambda    
  compileOptions{ 
    sourceCompatibility JavaVersion.VERSION_1_8 
    targetCompatibility JavaVersion.VERSION_1_8 
  } 
} 
 
dependencies { 
  compile fileTree(dir: 'libs', include: ['*.jar']) 
  androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 
    exclude group: 'com.android.support', module: 'support-annotations' 
  }) 
  compile 'com.android.support:appcompat-v7:24.1.1' 
  testCompile 'junit:junit:4.12' 
 
  //OKHttp 
  compile 'com.squareup.okhttp3:okhttp:3.6.0' 
  //RxJava RxAndroid          
  compile 'io.reactivex.rxjava2:rxandroid:2.0.1' 
  compile 'io.reactivex.rxjava2:rxjava:2.0.1' 
} 
OKHttp 와 RxJava,RxAndroid 는 모두 최신 버 전 을 사용 하고 자바 8 을 설정 합 니 다.
레이아웃 파일
이어서 레이아웃 파일 을 쓰기 시작 합 니 다.

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  xmlns:tools="http://schemas.android.com/tools" 
  android:id="@+id/activity_main" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  android:paddingBottom="@dimen/activity_vertical_margin" 
  android:paddingLeft="@dimen/activity_horizontal_margin" 
  android:paddingRight="@dimen/activity_horizontal_margin" 
  android:paddingTop="@dimen/activity_vertical_margin" 
  android:orientation="vertical" 
  tools:context="com.lanou3g.downdemo.MainActivity"> 
 
  <LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal"> 
    <ProgressBar 
      android:id="@+id/main_progress1" 
      android:layout_width="0dp" 
      android:layout_weight="1" 
      android:layout_height="match_parent" 
      style="@style/Widget.AppCompat.ProgressBar.Horizontal" /> 
    <Button 
      android:id="@+id/main_btn_down1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="  1"/> 
    <Button 
      android:id="@+id/main_btn_cancel1" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="  1"/> 
  </LinearLayout> 
  <LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal"> 
    <ProgressBar 
      android:id="@+id/main_progress2" 
      android:layout_width="0dp" 
      android:layout_weight="1" 
      android:layout_height="match_parent" 
      style="@style/Widget.AppCompat.ProgressBar.Horizontal" /> 
    <Button 
      android:id="@+id/main_btn_down2" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="  2"/> 
    <Button 
      android:id="@+id/main_btn_cancel2" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="  2"/> 
  </LinearLayout> 
  <LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal"> 
    <ProgressBar 
      android:id="@+id/main_progress3" 
      android:layout_width="0dp" 
      android:layout_weight="1" 
      android:layout_height="match_parent" 
      style="@style/Widget.AppCompat.ProgressBar.Horizontal" /> 
    <Button 
      android:id="@+id/main_btn_down3" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="  3"/> 
    <Button 
      android:id="@+id/main_btn_cancel3" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="  3"/> 
  </LinearLayout> 
</LinearLayout> 
대충 이렇게 생 겼 어 요.

3 개의 ProgressBar 는 진 도 를 표시 하기 위해 서 입 니 다.각 ProgressBar 는 2 개의 Button 에 대응 합 니 다.하 나 는 다운 로드 를 시작 하 는 것 이 고 하 나 는 다운 로드 를 일시 정지(취소)하 는 것 입 니 다.여기 서 설명 해 야 할 것 은 다운로드 에 있어 서 일시 정지 와 취 소 는 다 르 지 않 습 니 다.취소 할 때 임시 파일 을 모두 삭제 하 는 것 을 제외 하고 이 예 에서 그들 둘 을 구분 하지 않 습 니 다.
Application
저 희 는 파일 경 로 를 사용 해 야 합 니 다.전체 Context 가 비교적 편리 할 것 입 니 다.응용 프로그램 도 Context 의 하위 클래스 입 니 다.이 를 사용 하 는 것 이 가장 편리 하기 때문에 저 희 는 하나의 종 류 를 써 서 응용 프로그램 을 계승 합 니 다.

package com.lanou3g.downdemo; 
 
import android.app.Application; 
import android.content.Context; 
 
/** 
 * Created by     on 2017/2/2. 
 */ 
 
public class MyApp extends Application { 
  public static Context sContext;//   Context   
 
  @Override 
  public void onCreate() { 
    super.onCreate(); 
    sContext = this; 
  } 
} 
우 리 는 전체적인 Context 대상 을 얻 으 려 는 것 을 볼 수 있다.
Google 은 AndroidManifest 에 애플 리 케 이 션 을 등록 하고 필요 한 권한 을 부여 합 니 다.

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
  package="com.lanou3g.downdemo"> 
   
  <!--    --> 
  <uses-permission android:name="android.permission.INTERNET"/> 
 
  <application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:supportsRtl="true" 
    android:name=".MyApp" 
    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> 
  </application> 
 
</manifest> 
애플 리 케 이 션 탭 에 name 속성 을 추가 하여 애플 리 케 이 션 을 가리 키 는 네트워크 권한 만 필요 합 니 다.
DownloadManager
다음은 핵심 코드 입 니 다.바로 저희 DownloadManager 입 니 다.먼저 코드 를 올 립 니 다.

package com.lanou3g.downdemo; 
 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.util.HashMap; 
import java.util.concurrent.atomic.AtomicReference; 
 
import io.reactivex.Observable; 
import io.reactivex.ObservableEmitter; 
import io.reactivex.ObservableOnSubscribe; 
import io.reactivex.android.schedulers.AndroidSchedulers; 
import io.reactivex.schedulers.Schedulers; 
import okhttp3.Call; 
import okhttp3.OkHttpClient; 
import okhttp3.Request; 
import okhttp3.Response; 
 
/** 
 * Created by     on 2017/2/2. 
 */ 
 
public class DownloadManager { 
 
  private static final AtomicReference<DownloadManager> INSTANCE = new AtomicReference<>(); 
  private HashMap<String, Call> downCalls;//            
  private OkHttpClient mClient;//OKHttpClient; 
 
  //        
  public static DownloadManager getInstance() { 
    for (; ; ) { 
      DownloadManager current = INSTANCE.get(); 
      if (current != null) { 
        return current; 
      } 
      current = new DownloadManager(); 
      if (INSTANCE.compareAndSet(null, current)) { 
        return current; 
      } 
    } 
  } 
 
  private DownloadManager() { 
    downCalls = new HashMap<>(); 
    mClient = new OkHttpClient.Builder().build(); 
  } 
 
  /** 
   *      
   * 
   * @param url               
   * @param downLoadObserver         
   */ 
  public void download(String url, DownLoadObserver downLoadObserver) { 
    Observable.just(url) 
        .filter(s -> !downCalls.containsKey(s))//call map    ,       ,       
        .flatMap(s -> Observable.just(createDownInfo(s))) 
        .map(this::getRealFileName)//       ,        
        .flatMap(downloadInfo -> Observable.create(new DownloadSubscribe(downloadInfo)))//   
        .observeOn(AndroidSchedulers.mainThread())//       
        .subscribeOn(Schedulers.io())//       
        .subscribe(downLoadObserver);//      
 
  } 
 
  public void cancel(String url) { 
    Call call = downCalls.get(url); 
    if (call != null) { 
      call.cancel();//   
    } 
    downCalls.remove(url); 
  } 
 
  /** 
   *   DownInfo 
   * 
   * @param url      
   * @return DownInfo 
   */ 
  private DownloadInfo createDownInfo(String url) { 
    DownloadInfo downloadInfo = new DownloadInfo(url); 
    long contentLength = getContentLength(url);//       
    downloadInfo.setTotal(contentLength); 
    String fileName = url.substring(url.lastIndexOf("/")); 
    downloadInfo.setFileName(fileName); 
    return downloadInfo; 
  } 
 
  private DownloadInfo getRealFileName(DownloadInfo downloadInfo) { 
    String fileName = downloadInfo.getFileName(); 
    long downloadLength = 0, contentLength = downloadInfo.getTotal(); 
    File file = new File(MyApp.sContext.getFilesDir(), fileName); 
    if (file.exists()) { 
      //     ,       ,       
      downloadLength = file.length(); 
    } 
    //     ,          
    int i = 1; 
    while (downloadLength >= contentLength) { 
      int dotIndex = fileName.lastIndexOf("."); 
      String fileNameOther; 
      if (dotIndex == -1) { 
        fileNameOther = fileName + "(" + i + ")"; 
      } else { 
        fileNameOther = fileName.substring(0, dotIndex) 
            + "(" + i + ")" + fileName.substring(dotIndex); 
      } 
      File newFile = new File(MyApp.sContext.getFilesDir(), fileNameOther); 
      file = newFile; 
      downloadLength = newFile.length(); 
      i++; 
    } 
    //         /   
    downloadInfo.setProgress(downloadLength); 
    downloadInfo.setFileName(file.getName()); 
    return downloadInfo; 
  } 
 
  private class DownloadSubscribe implements ObservableOnSubscribe<DownloadInfo> { 
    private DownloadInfo downloadInfo; 
 
    public DownloadSubscribe(DownloadInfo downloadInfo) { 
      this.downloadInfo = downloadInfo; 
    } 
 
    @Override 
    public void subscribe(ObservableEmitter<DownloadInfo> e) throws Exception { 
      String url = downloadInfo.getUrl(); 
      long downloadLength = downloadInfo.getProgress();//         
      long contentLength = downloadInfo.getTotal();//       
      //       
      e.onNext(downloadInfo); 
 
      Request request = new Request.Builder() 
          //       ,    ,                  
          .addHeader("RANGE", "bytes=" + downloadLength + "-" + contentLength) 
          .url(url) 
          .build(); 
      Call call = mClient.newCall(request); 
      downCalls.put(url, call);//      call ,     
      Response response = call.execute(); 
 
      File file = new File(MyApp.sContext.getFilesDir(), downloadInfo.getFileName()); 
      InputStream is = null; 
      FileOutputStream fileOutputStream = null; 
      try { 
        is = response.body().byteStream(); 
        fileOutputStream = new FileOutputStream(file, true); 
        byte[] buffer = new byte[2048];//    2kB 
        int len; 
        while ((len = is.read(buffer)) != -1) { 
          fileOutputStream.write(buffer, 0, len); 
          downloadLength += len; 
          downloadInfo.setProgress(downloadLength); 
          e.onNext(downloadInfo); 
        } 
        fileOutputStream.flush(); 
        downCalls.remove(url); 
      } finally { 
        //  IO  
        IOUtil.closeAll(is, fileOutputStream); 
 
      } 
      e.onComplete();//   
    } 
  } 
 
  /** 
   *        
   * 
   * @param downloadUrl 
   * @return 
   */ 
  private long getContentLength(String downloadUrl) { 
    Request request = new Request.Builder() 
        .url(downloadUrl) 
        .build(); 
    try { 
      Response response = mClient.newCall(request).execute(); 
      if (response != null && response.isSuccessful()) { 
        long contentLength = response.body().contentLength(); 
        response.close(); 
        return contentLength == 0 ? DownloadInfo.TOTAL_ERROR : contentLength; 
      } 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
    return DownloadInfo.TOTAL_ERROR; 
  } 
 
 
} 
코드 가 좀 길 어서 관건 적 인 부분 에 주석 을 달 았 습 니 다.중요 한 부분 을 골 라 보 겠 습 니 다.
우선,우 리 는 하나의 예 류 입 니 다.우 리 는 OKHttpClient 하나만 다운로드 하면 충분 합 니 다.그래서 우 리 는 구조 방법 을 개인 적 으로 사용 합 니 다.하나의 인 스 턴 스 를 얻 는 방법 은 바로 이 getInstance()입 니 다.물론 여러분 은 다른 방식 으로 단일 예 를 실현 하 셔 도 됩 니 다.그리고 저 희 는 구조 방법 에서 HttpClient 를 초기 화하 고 HashMap 을 초기 화하 여 모든 네트워크 요청 을 넣 으 면 다운 로드 를 취소 할 때 url 에 대응 하 는 네트워크 요청 을 찾 아 취소 하면 됩 니 다.
다음은 핵심 적 인 download 방법 입 니 다.먼저 매개 변수 입 니 다.첫 번 째 매개 변수 url 은 말 할 필요 도 없 이 요청 한 사이트 입 니 다.두 번 째 매개 변 수 는 Observer 대상 입 니 다.우 리 는 RxJava 를 사용 하고 복잡 한 방법 이 별로 없 기 때문에 인 터 페 이 스 를 따로 쓰 지 않 고 Observer 대상 에 게 감 사 를 드 립 니 다.다음은 DownloadObserver 의 코드 입 니 다.

package com.lanou3g.downdemo; 
 
import io.reactivex.Observer; 
import io.reactivex.disposables.Disposable; 
 
/** 
 * Created by     on 2017/2/2. 
 */ 
 
public abstract class DownLoadObserver implements Observer<DownloadInfo> { 
  protected Disposable d;//             
  protected DownloadInfo downloadInfo; 
  @Override 
  public void onSubscribe(Disposable d) { 
    this.d = d; 
  } 
 
  @Override 
  public void onNext(DownloadInfo downloadInfo) { 
    this.downloadInfo = downloadInfo; 
  } 
 
  @Override 
  public void onError(Throwable e) { 
    e.printStackTrace(); 
  } 
 
 
} 
RxJava 2 에서 이 Observer 는 약간 변화 가 있 습 니 다.관찰 자 를 등록 할 때 onSubscribe 방법 을 호출 합 니 다.이 방법 은 인 자 는 등록 을 취소 하 는 데 사 용 됩 니 다.이러한 변경 은 더욱 유연 하 게 감청 자가 감청 을 취소 할 수 있 습 니 다.저희 의 진도 정 보 는 계속 전송 되 는 onNext 방법 에서 다운로드 에 필요 한 내용 을 DownloadInfo 라 고 합 니 다.

package com.lanou3g.downdemo; 
 
/** 
 * Created by     on 2017/2/2. 
 *      
 */ 
 
public class DownloadInfo { 
  public static final long TOTAL_ERROR = -1;//       
  private String url; 
  private long total; 
  private long progress; 
  private String fileName; 
   
  public DownloadInfo(String url) { 
    this.url = url; 
  } 
 
  public String getUrl() { 
    return url; 
  } 
 
  public String getFileName() { 
    return fileName; 
  } 
 
  public void setFileName(String fileName) { 
    this.fileName = fileName; 
  } 
 
  public long getTotal() { 
    return total; 
  } 
 
  public void setTotal(long total) { 
    this.total = total; 
  } 
 
  public long getProgress() { 
    return progress; 
  } 
 
  public void setProgress(long progress) { 
    this.progress = progress; 
  } 
} 
이 종 류 는 기본 적 인 정보 입 니 다.totalk 은 다운로드 해 야 할 파일 의 총 크기 입 니 다.progress 는 현재 다운로드 의 진도 입 니 다.그러면 다운로드 의 진도 정 보 를 계산 할 수 있 습 니 다.
이 어 DownloadManager 의 download 방법 을 살 펴 보 겠 습 니 다.먼저 url 을 통 해 Observable 대상 을 만 든 다음 filter 연산 자 를 통 해 걸 러 냅 니 다.현재 이 url 에 대응 하 는 내용 을 다운로드 하고 있다 면 다운로드 하지 않 습 니 다.
다음은 createDownInfo 를 호출 하여 Observable 대상 을 다시 만 듭 니 다.여 기 는 맵 으로 도 가능 합 니 다.createDownInfo 라 는 방법 에 서 는 getContentLength 를 호출 하여 서버 의 파일 크기 를 가 져 옵 니 다.이 방법의 코드 를 볼 수 있 습 니 다.

/** 
  *        
  * 
  * @param downloadUrl 
  * @return 
  */ 
  private long getContentLength(String downloadUrl) { 
    Request request = new Request.Builder() 
        .url(downloadUrl) 
        .build(); 
    try { 
      Response response = mClient.newCall(request).execute(); 
      if (response != null && response.isSuccessful()) { 
        long contentLength = response.body().contentLength(); 
        response.close(); 
        return contentLength == 0 ? DownloadInfo.TOTAL_ERROR : contentLength; 
      } 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
    return DownloadInfo.TOTAL_ERROR; 
  } 
이 를 통 해 알 수 있 듯 이 OK 를 통 해 네트워크 요청 을 한 번 하고 돌아 오 는 헤더 정보 에서 파일 의 크기 정 보 를 얻 을 수 있 습 니 다.보통 이 정 보 는 받 을 수 있 습 니 다.사이트 주 소 를 다운로드 하 는 것 이 자원 파일 을 직접 가리 키 는 것 이 아니 라 자신 이 직접 쓴 Servlet 이 아니라면 백 스테이지 직원 과 소통 해 야 합 니 다.이번 네트워크 요청 은 진정 으로 파일 을 다운로드 하지 않 았 습 니 다.크기 를 요청 하면 끝 납 니 다.구체 적 인 이 유 는 뒤에서 데 이 터 를 요청 할 때 설명 합 니 다.
이어서 다운로드 방법
파일 크기 를 가 져 오 면 하 드 디스크 에서 파일 을 찾 을 수 있 습 니 다.getRealFileName 방법 이 호출 되 었 습 니 다.

private DownloadInfo getRealFileName(DownloadInfo downloadInfo) { 
    String fileName = downloadInfo.getFileName(); 
    long downloadLength = 0, contentLength = downloadInfo.getTotal(); 
    File file = new File(MyApp.sContext.getFilesDir(), fileName); 
    if (file.exists()) { 
      //     ,       ,       
      downloadLength = file.length(); 
    } 
    //     ,          
    int i = 1; 
    while (downloadLength >= contentLength) { 
      int dotIndex = fileName.lastIndexOf("."); 
      String fileNameOther; 
      if (dotIndex == -1) { 
        fileNameOther = fileName + "(" + i + ")"; 
      } else { 
        fileNameOther = fileName.substring(0, dotIndex) 
            + "(" + i + ")" + fileName.substring(dotIndex); 
      } 
      File newFile = new File(MyApp.sContext.getFilesDir(), fileNameOther); 
      file = newFile; 
      downloadLength = newFile.length(); 
      i++; 
    } 
    //         /   
    downloadInfo.setProgress(downloadLength); 
    downloadInfo.setFileName(file.getName()); 
    return downloadInfo; 
  } 
이 방법 은 로 컬 에 다운로드 한 파일 이 있 는 지 확인 하 는 것 입 니 다.있 으 면 로 컬 파일 의 크기 와 서버 에 있 는 데이터 의 크기 를 다시 한 번 판단 하 는 것 입 니 다.같은 것 이 라면 다운로드 가 완료 되 었 음 을 증명 하고(1)같은 파일 이 되 는 것 입 니 다.로 컬 파일 의 크기 가 서버 에 있 는 것 보다 작 으 면 다운로드 가 반 으로 끊 겼 음 을 증명 합 니 다.그러면 진도 정 보 를 저장 하고 파일 이름 도 저장 하고 다 보고 다운 로드 방법 으로 돌아 갑 니 다.
그 후에 진정한 네트워크 요청 이 시작 되 었 습 니 다.여기에 Observable OnSubscribe 인 터 페 이 스 를 실현 하 는 내부 클래스 를 썼 습 니 다.이 인터페이스 도 RxJava 2 의 것 입 니 다.물건 은 예전 과 마찬가지 로 이름 만 바 꾼 것 같 습 니 다.코드 를 보 세 요.

private class DownloadSubscribe implements ObservableOnSubscribe<DownloadInfo> { 
    private DownloadInfo downloadInfo; 
 
    public DownloadSubscribe(DownloadInfo downloadInfo) { 
      this.downloadInfo = downloadInfo; 
    } 
 
    @Override 
    public void subscribe(ObservableEmitter<DownloadInfo> e) throws Exception { 
      String url = downloadInfo.getUrl(); 
      long downloadLength = downloadInfo.getProgress();//         
      long contentLength = downloadInfo.getTotal();//       
      //       
      e.onNext(downloadInfo); 
 
      Request request = new Request.Builder() 
          //       ,    ,                  
          .addHeader("RANGE", "bytes=" + downloadLength + "-" + contentLength) 
          .url(url) 
          .build(); 
      Call call = mClient.newCall(request); 
      downCalls.put(url, call);//      call ,     
      Response response = call.execute(); 
 
      File file = new File(MyApp.sContext.getFilesDir(), downloadInfo.getFileName()); 
      InputStream is = null; 
      FileOutputStream fileOutputStream = null; 
      try { 
        is = response.body().byteStream(); 
        fileOutputStream = new FileOutputStream(file, true); 
        byte[] buffer = new byte[2048];//    2kB 
        int len; 
        while ((len = is.read(buffer)) != -1) { 
          fileOutputStream.write(buffer, 0, len); 
          downloadLength += len; 
          downloadInfo.setProgress(downloadLength); 
          e.onNext(downloadInfo); 
        } 
        fileOutputStream.flush(); 
        downCalls.remove(url); 
      } finally { 
        //  IO  
        IOUtil.closeAll(is, fileOutputStream); 
 
      } 
      e.onComplete();//   
    } 
  } 
subscribe 방법
먼저 url,현재 진행 정보 와 파일 의 총 크기 를 가 져 온 다음 에 네트워크 요청 을 시작 합 니 다.이번 네트워크 요청 시 헤더 정 보 를 추가 해 야 합 니 다.

.addHeader("RANGE", "bytes=" + downloadLength + "-" + contentLength) 
이 헤더 정 보 는 다운로드 범위 가 얼마 인지,downloadLength 는 어디서부터 다운로드 하 는 지,contentLength 는 어디 까지 다운로드 하 는 지,끊 기 려 면 이 헤드 를 추가 해 야 합 니 다.입력 흐름 이 몇 바이트 를 뛰 어 넘 는 형식 으로 는 안 됩 니 다.따라서 이 정 보 를 성공 적 으로 추가 하려 면 이 url 에 2 번 요청 하고 한 번 에 총 길 이 를 받 아야 합 니 다.로 컬 에서 절반 의 데 이 터 를 다운로드 하 는 지 여 부 를 판단 하기 위해 두 번 째 에 야 진정한 읽 기 흐름 을 시작 하여 네트워크 요청 을 하기 시 작 했 습 니 다.파일 이 다운로드 가 완료 되 지 않 았 을 때 사용자 정의 접 두 사 를 추가 하고 다운로드 가 완료 되면 이 접 두 사 를 취소 하면 두 번 요청 할 필요 가 없 을 것 입 니 다.
다음은 정상 적 인 네트워크 요청 입 니 다.로 컬 에 파일 을 썼 습 니 다.로 컬 에 파일 을 썼 습 니 다.인터넷 은 대부분 RandomAccessFile 과 같은 종 류 를 사 용 했 습 니 다.그러나 여러 부분 을 연결 하지 않 으 면 필요 하지 않 습 니 다.출력 흐름 을 직접 사용 하면 됩 니 다.출력 흐름 의 구조 방법 에 true 인 자 를 추가 하면 원래 파일 뒤에 데 이 터 를 추가 하면 됩 니 다.순환 에서...onNext 방법 을 계속 호출 하여 진도 정 보 를 보 냅 니 다.다 쓴 후에 스 트림 을 끄 는 것 을 잊 지 마 세 요.동시에 call 대상 을 hashMap 에서 제거 합 니 다.여기 IOUtil 을 써 서 스 트림 을 닫 습 니 다.

package com.lanou3g.downdemo; 
 
import java.io.Closeable; 
import java.io.IOException; 
 
/** 
 * Created by     on 2017/2/2. 
 */ 
 
public class IOUtil { 
  public static void closeAll(Closeable... closeables){ 
    if(closeables == null){ 
      return; 
    } 
    for (Closeable closeable : closeables) { 
      if(closeable!=null){ 
        try { 
          closeable.close(); 
        } catch (IOException e) { 
          e.printStackTrace(); 
        } 
      } 
    } 
  } 
} 
사실은 빈 것 인지 아 닌 지 를 하나씩 판단 하고 닫 을 뿐이다.
이렇게 download 방법 이 완성 되 었 습 니 다.나머지 는 스 레 드 전환,관찰자 등록 입 니 다.
MainActivity
마지막 으로 aty 코드 입 니 다.

package com.lanou3g.downdemo; 
 
import android.net.Uri; 
import android.support.annotation.IdRes; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.ProgressBar; 
import android.widget.Toast; 
 
public class MainActivity extends AppCompatActivity implements View.OnClickListener { 
  private Button downloadBtn1, downloadBtn2, downloadBtn3; 
  private Button cancelBtn1, cancelBtn2, cancelBtn3; 
  private ProgressBar progress1, progress2, progress3; 
  private String url1 = "http://192.168.31.169:8080/out/dream.flac"; 
  private String url2 = "http://192.168.31.169:8080/out/music.mp3"; 
  private String url3 = "http://192.168.31.169:8080/out/code.zip"; 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
 
    downloadBtn1 = bindView(R.id.main_btn_down1); 
    downloadBtn2 = bindView(R.id.main_btn_down2); 
    downloadBtn3 = bindView(R.id.main_btn_down3); 
 
    cancelBtn1 = bindView(R.id.main_btn_cancel1); 
    cancelBtn2 = bindView(R.id.main_btn_cancel2); 
    cancelBtn3 = bindView(R.id.main_btn_cancel3); 
 
    progress1 = bindView(R.id.main_progress1); 
    progress2 = bindView(R.id.main_progress2); 
    progress3 = bindView(R.id.main_progress3); 
 
    downloadBtn1.setOnClickListener(this); 
    downloadBtn2.setOnClickListener(this); 
    downloadBtn3.setOnClickListener(this); 
 
    cancelBtn1.setOnClickListener(this); 
    cancelBtn2.setOnClickListener(this); 
    cancelBtn3.setOnClickListener(this); 
  } 
 
  @Override 
  public void onClick(View v) { 
    switch (v.getId()) { 
      case R.id.main_btn_down1: 
        DownloadManager.getInstance().download(url1, new DownLoadObserver() { 
          @Override 
          public void onNext(DownloadInfo value) { 
            super.onNext(value); 
            progress1.setMax((int) value.getTotal()); 
            progress1.setProgress((int) value.getProgress()); 
          } 
 
          @Override 
          public void onComplete() { 
            if(downloadInfo != null){ 
              Toast.makeText(MainActivity.this, 
                  downloadInfo.getFileName() + "-DownloadComplete", 
                  Toast.LENGTH_SHORT).show(); 
            } 
          } 
        }); 
        break; 
      case R.id.main_btn_down2: 
        DownloadManager.getInstance().download(url2, new DownLoadObserver() { 
          @Override 
          public void onNext(DownloadInfo value) { 
            super.onNext(value); 
            progress2.setMax((int) value.getTotal()); 
            progress2.setProgress((int) value.getProgress()); 
          } 
 
          @Override 
          public void onComplete() { 
            if(downloadInfo != null){ 
              Toast.makeText(MainActivity.this, 
                  downloadInfo.getFileName() + Uri.encode("    "), 
                  Toast.LENGTH_SHORT).show(); 
            } 
          } 
        }); 
        break; 
      case R.id.main_btn_down3: 
        DownloadManager.getInstance().download(url3, new DownLoadObserver() { 
          @Override 
          public void onNext(DownloadInfo value) { 
            super.onNext(value); 
            progress3.setMax((int) value.getTotal()); 
            progress3.setProgress((int) value.getProgress()); 
          } 
 
          @Override 
          public void onComplete() { 
            if(downloadInfo != null){ 
              Toast.makeText(MainActivity.this, 
                  downloadInfo.getFileName() + "    ", 
                  Toast.LENGTH_SHORT).show(); 
            } 
          } 
        }); 
        break; 
      case R.id.main_btn_cancel1: 
        DownloadManager.getInstance().cancel(url1); 
        break; 
      case R.id.main_btn_cancel2: 
        DownloadManager.getInstance().cancel(url2); 
        break; 
      case R.id.main_btn_cancel3: 
        DownloadManager.getInstance().cancel(url3); 
        break; 
    } 
  } 
   
  private <T extends View> T bindView(@IdRes int id){ 
    View viewById = findViewById(id); 
    return (T) viewById; 
  } 
} 
Activity 에 서 는 아무것도 아 닙 니 다.바로 감청 등록,다운로드 시작,다운로드 취소 입 니 다.다음은 효 과 를 살 펴 보 겠 습 니 다.
실행 효과

여러 개의 다운 로드 를 볼 수 있 습 니 다.정지점 전송 이 모두 성 공 했 습 니 다.마지막 으로 제 파일 주 소 는 제 랜 입 니 다.여러분 이 쓸 때 바 꾸 는 것 을 잊 지 마 세 요.
코드 주소:demo
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기