鱼C论坛

 找回密码
 立即注册
查看: 2108|回复: 0

[学习笔记] android programing 10.6

[复制链接]
发表于 2017-11-12 10:18:26 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
这个程序代码比较多,一上午总算给敲完了,(注:所有java文件都建在mainactivity.java旁边)。新建项目,然后新建DownLoadListener.java
  1. package com.example.xinwei.servicebestpractice;

  2. /**
  3. * Created by xinwei on 2017/11/12.
  4. */

  5. public interface DownLoadListener {
  6.     void onProgress(int progress);
  7.     void onSuccess();
  8.     void onFailed();
  9.     void onPause();
  10.     void onCanceled();
  11. }
复制代码

然后新建服务(要选取service选项来新建这个文件)DownLoadTask.java
  1. package com.example.xinwei.servicebestpractice;

  2. import android.os.AsyncTask;
  3. import android.os.Environment;

  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.RandomAccessFile;

  8. import okhttp3.OkHttpClient;
  9. import okhttp3.Request;
  10. import okhttp3.Response;

  11. /**
  12. * Created by xinwei on 2017/11/12.
  13. */

  14. public class DownLoadTask extends AsyncTask<String,Integer,Integer> {

  15.     public static final int TYPE_SUCCESS=0;
  16.     public static final int TYPE_FAILED=1;
  17.     public static final int TYPE_PAUSED=2;
  18.     public static final int TYPE_CANCELED=3;

  19.     private DownLoadListener listener;

  20.     private boolean isCanceled=false;

  21.     private boolean isPaused=false;

  22.     private int lastProgress;

  23.     public DownLoadTask(DownLoadListener listener){
  24.         this.listener=listener;
  25.     }
  26.     @Override
  27.     protected Integer doInBackground(String... params) {
  28.         InputStream is=null;
  29.         RandomAccessFile saveFile=null;
  30.         File file=null;
  31.         long downloadlength=0;
  32.         String downloadUrl=params[0];
  33.         String filename=downloadUrl.substring(downloadUrl.lastIndexOf("/"));
  34.         String directory= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
  35.         file=new File(directory+filename);
  36.         if (file.exists()){
  37.             downloadlength=file.length();
  38.         }
  39.         long contentLength= 0;
  40.         try {
  41.             contentLength = getContentLength(downloadUrl);
  42.         } catch (IOException e) {
  43.             e.printStackTrace();
  44.         }
  45.         if (contentLength == 0) {
  46.             return TYPE_FAILED;
  47.         }else if (contentLength==downloadlength){
  48.             return TYPE_SUCCESS;
  49.         }
  50.         OkHttpClient client=new OkHttpClient();
  51.         Request request=new Request.Builder()
  52.                 .addHeader("RANGE","bytes="+downloadlength+"-")
  53.                 .url(downloadUrl)
  54.                 .build();
  55.         try {
  56.             Response response=client.newCall(request).execute();
  57.             if (response!=null){
  58.                 is=response.body().byteStream();
  59.                 saveFile=new RandomAccessFile(file,"rw");
  60.                 saveFile.seek(downloadlength);
  61.                 byte[] b=new byte[1024];
  62.                 int total=0;
  63.                 int len;
  64.                 while((len=is.read(b))!=-1){
  65.                     if (isCanceled){
  66.                         return TYPE_FAILED;
  67.                     }else if (isPaused){
  68.                         return TYPE_PAUSED;
  69.                     }else{
  70.                         total+=len;
  71.                         saveFile.write(b,0,len);
  72.                         int progress=(int)((total+downloadlength)*100/contentLength);
  73.                         publishProgress(progress);
  74.                     }
  75.                 }
  76.                 response.body().close();
  77.                 return TYPE_SUCCESS;
  78.             }
  79.         } catch (IOException e) {
  80.             e.printStackTrace();
  81.         }finally {
  82.             try{
  83.                 if (is!=null){
  84.                     is.close();
  85.                 }
  86.                 if (saveFile!=null){
  87.                     saveFile.close();
  88.                 }
  89.                 if (isCanceled&&file!=null){
  90.                     file.delete();
  91.                 }
  92.             }catch (Exception e){
  93.                 e.printStackTrace();
  94.             }
  95.         }
  96.         return TYPE_FAILED;
  97.     }

  98.     @Override
  99.     protected void onProgressUpdate(Integer... values) {
  100.         super.onProgressUpdate(values);
  101.         int progress=values[0];
  102.         if (progress>lastProgress){
  103.             listener.onProgress(progress);
  104.             lastProgress=progress;
  105.         }
  106.     }

  107.     @Override
  108.     protected void onPostExecute(Integer status) {
  109.         super.onPostExecute(status);
  110.         switch (status){
  111.             case TYPE_SUCCESS:
  112.                 listener.onSuccess();
  113.                 break;
  114.             case TYPE_FAILED:
  115.                 listener.onFailed();
  116.                 break;
  117.             case TYPE_PAUSED:
  118.                 listener.onPause();
  119.                 break;
  120.             case TYPE_CANCELED:
  121.                 listener.onCanceled();
  122.                 break;
  123.             default:
  124.                 break;
  125.         }
  126.     }
  127.     public void pauseDownload(){
  128.         isPaused=true;
  129.     }
  130.     public void cancelDownload(){
  131.         isCanceled=true;
  132.     }
  133.     private long getContentLength(String downloadUrl)throws IOException{
  134.         OkHttpClient client=new OkHttpClient();
  135.         Request request=new Request.Builder()
  136.                 .url(downloadUrl)
  137.                 .build();
  138.         Response response=client.newCall(request).execute();
  139.         if (response!=null&&response.isSuccessful()){
  140.             long contentLength=response.body().contentLength();
  141.             response.close();
  142.             return contentLength;
  143.         }
  144.         return 0;
  145.     }
  146. }






复制代码

修改mainactivity.java
  1. package com.example.xinwei.servicebestpractice;

  2. import android.Manifest;
  3. import android.content.ComponentName;
  4. import android.content.Intent;
  5. import android.content.ServiceConnection;
  6. import android.content.pm.PackageManager;
  7. import android.os.IBinder;
  8. import android.support.annotation.NonNull;
  9. import android.support.v4.app.ActivityCompat;
  10. import android.support.v4.content.ContextCompat;
  11. import android.support.v7.app.AppCompatActivity;
  12. import android.os.Bundle;
  13. import android.view.View;
  14. import android.widget.Button;
  15. import android.widget.Toast;

  16. import static android.content.pm.PackageManager.PERMISSION_GRANTED;

  17. public class MainActivity extends AppCompatActivity implements View.OnClickListener{

  18.     private DownloadService.DownloadBinder downloadBinder;
  19.     private ServiceConnection connection=new ServiceConnection() {
  20.         @Override
  21.         public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
  22.             downloadBinder=(DownloadService.DownloadBinder)iBinder;
  23.         }

  24.         @Override
  25.         public void onServiceDisconnected(ComponentName componentName) {

  26.         }
  27.     };
  28.     @Override
  29.     protected void onCreate(Bundle savedInstanceState) {
  30.         super.onCreate(savedInstanceState);
  31.         setContentView(R.layout.activity_main);
  32.         Button startDownload=(Button)findViewById(R.id.start_download);
  33.         Button pauseDownload=(Button)findViewById(R.id.pause_download);
  34.         Button cancelDownload=(Button)findViewById(R.id.cancel_download);
  35.         startDownload.setOnClickListener(this);
  36.         pauseDownload.setOnClickListener(this);
  37.         cancelDownload.setOnClickListener(this);
  38.         Intent intent=new Intent(this,DownloadService.class);
  39.         startService(intent);
  40.         bindService(intent,connection,BIND_AUTO_CREATE);
  41.         if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PERMISSION_GRANTED){
  42.             ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
  43.         }
  44.     }

  45.     @Override
  46.     public void onClick(View view) {
  47.         if (downloadBinder==null){
  48.             return;
  49.         }
  50.         switch (view.getId()){
  51.             case R.id.start_download:
  52.                 String url="https://raw.githubusercontent.com/guolindev/eclipse/master/eclipse_inst-win64.exe";
  53.                 downloadBinder.startDownload(url);
  54.                 break;

  55.             case R.id.pause_download:
  56.                 downloadBinder.pauseDownload();
  57.                 break;

  58.             case R.id.cancel_download:
  59.                 downloadBinder.cancelDownload();
  60.                 break;
  61.             default:
  62.                 break;
  63.         }
  64.     }

  65.     @Override
  66.     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  67.         super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  68.         switch (requestCode){
  69.             case 1:
  70.                 if (grantResults.length>0&&grantResults[0]!= PackageManager.PERMISSION_GRANTED){
  71.                     Toast.makeText(this, "denied permission will not use program", Toast.LENGTH_SHORT).show();
  72.                     finish();
  73.                 }
  74.                 break;
  75.             default:
  76.         }
  77.     }

  78.     @Override
  79.     protected void onDestroy() {
  80.         super.onDestroy();
  81.         unbindService(connection);
  82.     }
  83. }
复制代码

修改activity_main.xml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"
  4.     xmlns:tools="http://schemas.android.com/tools"
  5.     android:layout_width="match_parent"
  6.     android:layout_height="match_parent"
  7.     android:orientation="vertical"
  8.     tools:context="com.example.xinwei.servicebestpractice.MainActivity">

  9.     <Button
  10.         android:id="@+id/start_download"
  11.         android:layout_width="match_parent"
  12.         android:layout_height="wrap_content"
  13.         android:text="start download"/>
  14.     <Button
  15.         android:id="@+id/pause_download"
  16.         android:layout_width="match_parent"
  17.         android:layout_height="wrap_content"
  18.         android:text="pause download"/>
  19.     <Button
  20.         android:id="@+id/cancel_download"
  21.         android:layout_width="match_parent"
  22.         android:layout_height="wrap_content"
  23.         android:text="cancel download"/>


  24. </LinearLayout>
复制代码

在AndroidManifest.xml里manifest标签下添加
  1. <uses-permission android:name="android.permission.INTERNET"/>
  2.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
复制代码

因为我这手机模拟器不太好使,内存卡出了点问题,所以就不演示了。

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-3-29 13:16

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表