Android之完整版的下载示例

终于写完了,但是感觉有时候不是太理解,书上有的说的很模糊,有时候甚至一带而过,不过这样也挺好的,能够锻炼一下自己的自学能力,对代码的理解能力。如果每段代码有大量的注释也不是很好,理解它的核心内容就可以了。

下面看看效果图:
这里写图片描述
这里写图片描述
这里写图片描述

DownloadTask.java

package com.example.lenovo.servicebestprectice;

import android.app.DownloadManager;
import android.os.AsyncTask;
import android.os.Environment;
import android.webkit.DownloadListener;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Lenovo on 2017/9/17.
 */

public class DownloadTask extends AsyncTask<String,Integer,Integer>{
    public static final int TYPE_SUCCESS = 0;
    public static final int TYPE_FAILED = 1;
    public static final int TYPE_PAUSE = 2;
    public static final int TYPE_CANCELED = 3;

    private DownLoadListener listener;
    private boolean isCanceled = false;
    private boolean isPause = false;
    private int lastProgress;
    public DownloadTask(DownLoadListener listener){
        this.listener = listener;
    }

    /*doInBackground方法 将在onPreExecute 方法执行后马上执行,该方法运行在后台线程中。
    * 这里将主要负责执行那些很耗时的后台处理工作。可以调用 publishProgress方法来更新实时的任务进度。
    * 该方法是抽象方法,子类必须实现。
    * */

    @Override
    protected Integer doInBackground(String... params) {
        InputStream is = null;
        RandomAccessFile saveFile = null;
        File file = null;

        long downloadedLength = 0;//记录已下载的文件长度
        String downloadUrl = params[0];
        String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
        String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
        file = new File(directory + fileName);
        if (file.exists()){
            downloadedLength = file.length();
        }
        long contentLength = getContentLength(downloadUrl);
        if (contentLength==0){
            return TYPE_FAILED;
        }else if (contentLength == downloadedLength){
            return TYPE_SUCCESS;
        }
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                //断点下载,指定从哪个字节下载
                .addHeader("RANGE","bytes = "+downloadedLength+"-")
                .url(downloadUrl)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response !=  null){
                is = response.body().byteStream();
                saveFile = new RandomAccessFile(file,"rw");
                saveFile.seek(downloadedLength);//跳过已下载的字节
                byte[] b = new byte[1024];
                int total = 0;
                int len ;
                while ((len = is.read(b))!=-1){
                    if (isCanceled){
                        return TYPE_CANCELED;
                    }else if (isPause){
                        return TYPE_PAUSE;
                    }else {
                        total+=len;
                        saveFile.write(b,0,len);
                        //计算已下载的百分比
                        int progress = (int) ((total+downloadedLength)*100/contentLength);
                        publishProgress(progress);
                    }
                }
                response.body().close();
                return TYPE_SUCCESS;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (is != null){
                        is.close();
                }
                if (saveFile!=null){
                    saveFile.close();
                }
                if (isCanceled && file!=null){
                    file.delete();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return TYPE_FAILED;
    }

    /*
    * onProgressUpdate(Progress…),在publishProgress方法被调用后,
    * UI 线程将调用这个方法从而在界面上展示任务的进展情况,例如通过一个进度条进行展示。
    * */
    @Override
    protected void onProgressUpdate(Integer... values) {
        int progress = values[0];
        if (progress > lastProgress){
            listener.onProgress(progress);
            lastProgress = progress;
        }
    }

    /*
    * 在doInBackground 执行完成后,onPostExecute 方法将被UI 线程调用,
    * 后台的计算结果将通过该方法传递到UI 线程,并且在界面上展示给用户.
    * */

    @Override
    protected void onPostExecute(Integer status) {
        switch (status){
            case TYPE_SUCCESS:
                listener.onSuccess();
                break;
            case TYPE_FAILED:
                listener.onFailed();
                break;
            case TYPE_PAUSE:
                listener.onPause();
                break;
            case TYPE_CANCELED:
                listener.onCanceled();
                break;
            default:
                break;
        }
    }
    public void pauseDownload(){
        isPause = true;
    }
    public void cancelDownload(){
        isCanceled = true;
    }

    private long getContentLength(String downloadUrl){
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(downloadUrl)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response!=null && response.isSuccessful()){
                long contentlength = response.body().contentLength();
                response.close();
                return contentlength;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
}

DownloadService.java

package com.example.lenovo.servicebestprectice;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.support.v7.app.NotificationCompat;
import android.webkit.DownloadListener;
import android.widget.Toast;

import java.io.File;

public class DownloadService extends Service {

    private DownloadTask downloadTask ;

    private String downloadUrl;

    private DownLoadListener listener = new DownLoadListener() {
        @Override
        public void onProgress(int profress) {
            getNotificationManager().notify(1,getNotification("Downloading...",profress));
        }

        @Override
        public void onSuccess() {
            downloadTask = null;
            //下载成功前将前台服务通知关闭,并创建一个下载成功的通知
            stopForeground(true);
            //触发getNotification通知
            getNotificationManager().notify(1,getNotification("Download success",-1));
            Toast.makeText(DownloadService.this, "Download Success", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onFailed() {
            downloadTask = null;
            //下载失败前将前台服务通知关闭,并创建一个下载失败的通知
            stopForeground(true);
            getNotificationManager().notify(1,getNotification("Download Failed",-1));
            Toast.makeText(DownloadService.this, "Download Failed", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onPause() {
            downloadTask = null;
            Toast.makeText(DownloadService.this, "paused", Toast.LENGTH_SHORT).show();
        }


        @Override
        public void onCanceled() {
            downloadTask = null;
            stopForeground(true);
            Toast.makeText(DownloadService.this, "Canceled", Toast.LENGTH_SHORT).show();
        }
    };

    public DownloadService() {
    }
    private DownloadBinder mBinder = new DownloadBinder();

    @Override
    public IBinder onBind(Intent intent) {
       return mBinder;
    }
    class DownloadBinder extends Binder{
        public void startDownload(String url){
            if (downloadTask == null){
                downloadUrl = url;
                downloadTask = new DownloadTask(listener);
                downloadTask.execute(downloadUrl);
                //为了让下载服务成为一个前台服务,我们还调用了startForeground()
                startForeground(1,getNotification("Downloading...",0));
                Toast.makeText(DownloadService.this, "Downloading...", Toast.LENGTH_SHORT).show();
            }
        }
        public void pauseDownload(){
            if (downloadTask!=null){
                downloadTask.pauseDownload();
            }
        }
        public void cancelDownload(){
            if (downloadTask!=null){
                downloadTask.cancelDownload();
            }else {
                if (downloadUrl!=null){
                    //取消下载时需要将文件删除,并将通知关闭
                    String fileName = downloadUrl.substring(downloadUrl.lastIndexOf("/"));
                    String directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
                    File file = new File(directory + fileName);
                    if (file.exists()){
                        file.delete();
                    }
                    getNotificationManager().cancel(1);
                    stopForeground(true);
                    Toast.makeText(DownloadService.this, "Canceled", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }

    private NotificationManager getNotificationManager(){
        //获取通知管理器
        return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }
    //用于显示下载进度的通知
    private Notification getNotification(String title,int progress){
        Intent intent = new Intent(this,MainActivity.class);
        // 创建一个PendingIntent,和Intent类似,不同的是由于不是马上调用,
        // 需要在下拉状态条出发的activity,所以采用的是PendingIntent,
        // 即点击Notification跳转启动到哪个Activity
        PendingIntent pi = PendingIntent.getActivity(this,0,intent,0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));
        builder.setContentIntent(pi);
        builder.setContentTitle(title);
        if (progress > 0){
            builder.setContentText(progress+"%");
            //第一个参数通知最大参数,
            //第二个参数传入通知的当前进度
            //第三个参数表示是否使用模糊的进度条
            builder.setProgress(100,progress,false);
        }
        return builder.build();
    }
}

MainActivity.java

package com.example.lenovo.servicebestprectice;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private DownloadService.DownloadBinder downloadBinder;
    private Button mBtnstartDownload,mBtnPauseDownload,mBtnCanceDownload;

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

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBtnstartDownload = (Button) findViewById(R.id.btn_start_download);
        mBtnPauseDownload = (Button) findViewById(R.id.btn_pause_download);
        mBtnCanceDownload = (Button) findViewById(R.id.btn_cancel_download);
        mBtnstartDownload.setOnClickListener(this);
        mBtnPauseDownload.setOnClickListener(this);
        mBtnCanceDownload.setOnClickListener(this);
        Intent intent = new Intent(this,DownloadService.class);
        startService(intent);//启动服务
        bindService(intent,connection,BIND_AUTO_CREATE);//绑定服务
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }
    }

    @Override
    public void onClick(View v) {
        if (downloadBinder == null){
            return;
        }
        switch (v.getId()){
            case R.id.btn_start_download:
                String url = "https://raw.githubusercontent.com/guolindev/eclipse/master/eclipse-inst-win64.exe";
                downloadBinder.startDownload(url);
                break;
            case R.id.btn_pause_download:
                downloadBinder.pauseDownload();
                break;
            case R.id.btn_cancel_download:
                downloadBinder.cancelDownload();
                break;
            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if (grantResults.length > 0 && grantResults[0] != PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(this, "拒绝权限无法使用程序", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    }
}

DownLoadListener.java

package com.example.lenovo.servicebestprectice;

/**
 * Created by Lenovo on 2017/9/17.
 */

public interface DownLoadListener {
    void onProgress(int profress);
    void onSuccess();
    void onFailed();
    void onPause();
    void onCanceled();
}

activity_main.xml

<?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/btn_start_download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Start Download"
        android:textAllCaps="false"
        />
    <Button
        android:id="@+id/btn_pause_download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Pause Download"
        android:textAllCaps="false"
        />
    <Button
        android:id="@+id/btn_cancel_download"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Cancel Download"
        android:textAllCaps="false"
        />

</LinearLayout>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
以下是一个使用Speex库进行回音消除的Android示例: 1.首先,你需要在你的Android项目中包含Speex库。你可以使用Speex的Java绑定版本,也可以使用Speex的C/C++版本并使用JNI进行调用。 2.接下来,你需要配置音频录制和播放。这可以通过使用Android的AudioRecord和AudioTrack类来完成。在录制和播放音频之前,你需要设置相应的参数,如采样率、声道数和位深度。 3.在录制音频期间,你需要使用Speex库对录制的音频进行回音消除。你可以使用Speex库中提供的SpeexEchoState结构体和相应的API来完成这个过程。以下是一个简单的示例: ```java int sampleRate = 16000; int bufferSize = AudioRecord.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT); AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION, sampleRate, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize); recorder.startRecording(); int frameSize = 160; short[] echoCancellationBuffer = new short[frameSize]; SpeexEchoState echoState = Speex.echo_state_init(frameSize, sampleRate); Speex.echo_ctl(echoState, SPEEX_ECHO_SET_SAMPLING_RATE, sampleRate); Speex.echo_ctl(echoState, SPEEX_ECHO_SET_FILTER_LENGTH, frameSize); Speex.echo_ctl(echoState, SPEEX_ECHO_GET_FRAME_SIZE, frameSize); while (isRecording) { short[] buffer = new short[frameSize]; recorder.read(buffer, 0, frameSize); Speex.echo_cancellation(echoState, buffer, echoCancellationBuffer, buffer); // TODO: Process the audio buffer } recorder.stop(); recorder.release(); Speex.echo_state_destroy(echoState); ``` 4.在播放音频期间,你需要使用Speex库对输出的音频进行回音抑制。你可以使用Speex库中提供的SpeexPreprocessState结构体和相应的API来完成这个过程。以下是一个简单的示例: ```java int sampleRate = 16000; int bufferSize = AudioTrack.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT); AudioTrack player = new AudioTrack(AudioManager.STREAM_VOICE_CALL, sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize, AudioTrack.MODE_STREAM); player.play(); int frameSize = 160; short[] noiseSuppressionBuffer = new short[frameSize]; SpeexPreprocessState preprocessState = Speex.preprocess_state_init(frameSize, sampleRate); Speex.preprocess_ctl(preprocessState, SPEEX_PREPROCESS_SET_DENOISE, 1); Speex.preprocess_ctl(preprocessState, SPEEX_PREPROCESS_SET_AGC, 1); Speex.preprocess_ctl(preprocessState, SPEEX_PREPROCESS_SET_AGC_LEVEL, 8000); Speex.preprocess_ctl(preprocessState, SPEEX_PREPROCESS_SET_DEREVERB, 1); while (isPlaying) { short[] buffer = new short[frameSize]; // TODO: Fill the audio buffer with audio data Speex.preprocess_run(preprocessState, buffer, noiseSuppressionBuffer); player.write(buffer, 0, frameSize); } player.stop(); player.release(); Speex.preprocess_state_destroy(preprocessState); ``` 注意:在实际使用中,你需要根据具体情况调整回音消除和回音抑制的参数,以达到最佳效果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值