其实第一行代码的例子我早就学习过了,现在手上一个项目需要使用到这些东西,准备在操作之前复习一下,就顺便发个博客加深一下自己对Android服务和文件下载这一块的理解,博客可能有点长我尽量写的详细一点便于理解。
1.首先新建一个Android项目
2.添加okhttp依赖,这里我们使用okhttp来访问网络,其实我是习惯使用http的,但是不可否认okhttp很强大
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.2.1‘ testCompile ‘junit:junit:4.12‘ compile ‘com.squareup.okhttp3:okhttp:3.4.1‘//就添加这一行 }
3.定义一个回调接口DownloadListener ,用于对下载状态的监听和对调
public interface DownloadListener { void onProgress(int progress);//通知当前下载进度 void onSuccess();//通知下载成功 void onFiled();//通知下载失败 void onPaused();//下载暂停 void inCanceled();//下载取消 }
4.开始编写下载功能。我们使用AsyncTask来实现,AsyncTask是Android提供的轻量级的异步类,我们可以再里面完成一些耗时的工作,比如下载
新建一个DownloadTask继承AsyncTask,这个代码有一丢丢长啊,首先我大概说下,下面主要的有三个函数,doInBackground用于执行下载逻辑,onProgressUpdate用于更新下载进度,onPostExecute用于通知最终结果,下面虽然代码长,我几乎所有的主要内容全给了备注,相信就算是新手也看的懂得
package com.example.dowmloadfile.Myclass; import android.os.AsyncTask; import android.os.Environment; import com.example.dowmloadfile.imp.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 海绵宝宝 on 2019/5/13. */ /**三个参数第一个为需要传入给后台的数据类型,第二个是进度显示类型,第三个为使用Integer作为反馈结果类型**/ 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_PAUSED=2;//下载暂停 public static final int TYPE_CANCELED=3;//下载取消 private DownloadListener downloadListener; private boolean isCanceled=false; private boolean isPaused=false; private int lastProgress; //通过DownLoadTask回调下载状态 public DownLoadTask(DownloadListener listener){ downloadListener=listener;//传入一个刚才定义的接口,用于回调 } @Override//后台执行具体的下载逻辑 protected Integer doInBackground(String... params) {//参数为下载的URL地址 InputStream is=null; RandomAccessFile savedFile=null; File file=null; try{ long downloadLength=0; String downloadUrl=params[0]; String fileName=downloadUrl.substring(downloadUrl.lastIndexOf("/"));//解析出下载的文件名 String derectory= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();//获取本地的下载文件夹的路径 file=new File(derectory+fileName); if (file.exists()){ downloadLength=file.length(); } long contentLength=getContentLength(downloadUrl);//读取下载文件的字节数 if (contentLength==0){//下载文件长度为0说明文件不存在,返回下载失败 return TYPE_FAILED; }else if (contentLength==downloadLength){//下载文件与本地文件大小一致说明已下载返回下载成功 return TYPE_SUCCESS; } OkHttpClient client=new OkHttpClient(); Request request=new Request.Builder().addHeader("RANGE","bytes="+downloadLength+"-").url(downloadUrl).build();//head用于告诉服务器我们从那个字节开始下载 Response response=client.newCall(request).execute(); if (response!=null){ //以java流的方式不断获取信息,不断写入本地 is=response.body().byteStream(); savedFile=new RandomAccessFile(file,"rw"); savedFile.seek(downloadLength);//跳过已经下载的字节 byte[] b=new byte[1024]; int total=0; int len; //查看过程中用户是否暂停或者取消 while((len=is.read(b))!=-1){ if (isCanceled){ return TYPE_CANCELED; }else if(isPaused){ return TYPE_PAUSED; }else { total+=len; savedFile.write(b,0,len); int progress=(int)((total+downloadLength)*100/contentLength);//计算当前进度 publishProgress(progress);//在通知中显示 } } response.body().close(); return TYPE_SUCCESS; }; }catch (Exception e){ e.printStackTrace(); }finally { try { if (is!=null){ is.close(); }else if (savedFile!=null){ savedFile.close(); }else if (isCanceled&&file!=null){ file.delete(); } }catch (Exception e){ e.printStackTrace(); } } return TYPE_FAILED; } @Override//用于比较下载进度然后使用onProgress来更改下载进度的通知 protected void onProgressUpdate(Integer... values) { int progress=values[0];//获取下载进度 if (progress>lastProgress){//如果进度发生了变化,那么更新进度显示 downloadListener.onProgress(progress); lastProgress=progress; } } @Override//根据传入的参数进行回调 protected void onPostExecute(Integer integer) { switch (integer) { case TYPE_SUCCESS: downloadListener.onSuccess(); break; case TYPE_FAILED: downloadListener.onFiled(); break; case TYPE_PAUSED: downloadListener.onPaused(); break; case TYPE_CANCELED: downloadListener.inCanceled(); default: break; }; } public void pauseDownload(){ isPaused=true; } public void cancelDownload(){ isCanceled=true; } //获取需要下载的文件长度 private long getContentLength(String downloadUrl)throws IOException{ OkHttpClient client=new OkHttpClient(); Request request=new Request.Builder().url(downloadUrl).build(); Response response=client.newCall(request).execute(); if(response!=null&&response.isSuccessful()){ long contentLength=response.body().contentLength(); response.close(); return contentLength; } return 0; } }
5.右击com.example.dowmloadfile-》New-》Service-》Service新建一个服务然后修改其中的代码
下面代码也比较长,简述一下就是,先创建了一个DownloadListener实现了我们之前建立的接口的具体方法,为了使DownloadService 可以和活动通信我们建立了一个DownloadBinder 将DownloadListener以参数形式传入,最后getNotification用于显示进度内容
package com.example.dowmloadfile.Myservice; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.graphics.BitmapFactory; import android.os.Binder; import android.os.Environment; import android.os.IBinder; import android.support.v4.app.NotificationCompat; import android.widget.Toast; import com.example.dowmloadfile.MainActivity; import com.example.dowmloadfile.Myclass.DownLoadTask; import com.example.dowmloadfile.R; import com.example.dowmloadfile.imp.DownloadListener; import java.io.File; public class DownloadService extends Service { private DownLoadTask downLoadTask; private String downloadUrl; //创建一个DownloadListener并实现其中的方法 private DownloadListener downloadListener=new DownloadListener() { @Override//以通知的方式显示进度条 public void onProgress(int progress) { //使用getNotificationManager函数构建一个用于显示下载进度的通知 //使用notify去触发这个通知 getNotificationManager().notify(1,getNotification("Download...",progress)); } @Override public void onSuccess() { downLoadTask=null; //关闭前台服务通知 //下面自己写了一个通知用于通知下载成功 stopForeground(true); getNotificationManager().notify(1,getNotification("download succeed",-1)); Toast.makeText(DownloadService.this,"Download Succeed",Toast.LENGTH_LONG).show(); String directory= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath(); } @Override public void onFiled() { downLoadTask=null; //关闭前台服务通知 stopForeground(true); getNotificationManager().notify(1,getNotification("download filed",-1)); Toast.makeText(DownloadService.this,"Download failed",Toast.LENGTH_LONG).show(); } @Override public void onPaused() { downLoadTask=null; Toast.makeText(DownloadService.this,"Download Paused",Toast.LENGTH_LONG).show(); } @Override public void inCanceled() { downLoadTask=null; //关闭前台服务通知 stopForeground(true); Toast.makeText(DownloadService.this,"Download canceled",Toast.LENGTH_LONG).show(); } }; //用于使服务可以和活动通信 private DownloadBinder mBinder=new DownloadBinder(); @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. return mBinder; } //用于使服务可以和活动通信 public class DownloadBinder extends Binder{ //开始下载 public void startDownload(String url){ if(downLoadTask==null){ downloadUrl=url; //创建一个DownLoadTask,将上面的downloadListener传入 downLoadTask=new DownLoadTask(downloadListener); //使用execute开启下载 downLoadTask.execute(downloadUrl); //startForeground使服务成为一个前台服务以创建持续运行的通知 startForeground(1,getNotification("download...",0)); Toast.makeText(DownloadService.this,"Download",Toast.LENGTH_LONG).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_LONG).show(); } } } } private NotificationManager getNotificationManager(){ return (NotificationManager)getSystemService(NOTIFICATION_SERVICE); } private Notification getNotification(String title,int progress){ Intent intent=new Intent(this, MainActivity.class); 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(); } }
6.后台的代码就是上面那些,剩下的就好理解多了,现在修改xml文件,定义三个按钮分别用于开始下载,暂停下载,取消下载
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/start" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="start download"/> <Button android:id="@+id/pause" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="start pause"/> <Button android:id="@+id/cancel" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="start cancel"/> </LinearLayout>
7.修改Main.java给按钮添加点击事件,将前台和我们写好的后台联系起来,主函数较为简单,细心一点都能看懂的
package com.example.dowmloadfile; import android.Manifest; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.os.IBinder; 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 com.example.dowmloadfile.Myservice.DownloadService; public class MainActivity extends AppCompatActivity implements View.OnClickListener{ private DownloadService.DownloadBinder downloadBinder; //ServiceConnection主要用于获取downloadBinder实例 private ServiceConnection connection=new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { //获取实例以便于在活动中调用其中的方法 downloadBinder=(DownloadService.DownloadBinder) service; } @Override public void onServiceDisconnected(ComponentName name) { } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button start=(Button)findViewById(R.id.start); Button pause=(Button)findViewById(R.id.pause); Button cancel=(Button)findViewById(R.id.cancel); start.setOnClickListener(this); pause.setOnClickListener(this); cancel.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 view){ if(downloadBinder==null) { return; } switch (view.getId()){ case R.id.start: String url="http://47.107.108.172:8080/Competition/fileUpload/xueyuanFile/1/10/12e1d4ba00aa43a1a69cf572d3d91816_关于举办第四届全国移动互联创新大赛的通知.pdf"; downloadBinder.startDownload(url); break; case R.id.pause: downloadBinder.pauseDownload(); break; case R.id.cancel: downloadBinder.cancelDownload(); break; default: break; } } @Override protected void onDestroy() { super.onDestroy(); //解除服务的绑定,否则可能会造成消息泄露 unbindService(connection); } }
8.此时Android应该已经帮我们注册好了权限,不过为了保险起见我们检查一下
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.dowmloadfile"> <uses-permission android:name="android.permission.INTERNET" /> <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=".Myservice.DownloadService" android:enabled="true" android:exported="true"></service> </application> </manifest>
9.现在程序就可以运行了