马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
这个程序代码比较多,一上午总算给敲完了,(注:所有java文件都建在mainactivity.java旁边)。新建项目,然后新建DownLoadListener.javapackage com.example.xinwei.servicebestpractice;
/**
* Created by xinwei on 2017/11/12.
*/
public interface DownLoadListener {
void onProgress(int progress);
void onSuccess();
void onFailed();
void onPause();
void onCanceled();
}
然后新建服务(要选取service选项来新建这个文件)DownLoadTask.javapackage com.example.xinwei.servicebestpractice;
import android.os.AsyncTask;
import android.os.Environment;
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 xinwei on 2017/11/12.
*/
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 listener;
private boolean isCanceled=false;
private boolean isPaused=false;
private int lastProgress;
public DownLoadTask(DownLoadListener listener){
this.listener=listener;
}
@Override
protected Integer doInBackground(String... params) {
InputStream is=null;
RandomAccessFile saveFile=null;
File file=null;
long downloadlength=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()){
downloadlength=file.length();
}
long contentLength= 0;
try {
contentLength = getContentLength(downloadUrl);
} catch (IOException e) {
e.printStackTrace();
}
if (contentLength == 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();
try {
Response response=client.newCall(request).execute();
if (response!=null){
is=response.body().byteStream();
saveFile=new RandomAccessFile(file,"rw");
saveFile.seek(downloadlength);
byte[] b=new byte[1024];
int total=0;
int len;
while((len=is.read(b))!=-1){
if (isCanceled){
return TYPE_FAILED;
}else if (isPaused){
return TYPE_PAUSED;
}else{
total+=len;
saveFile.write(b,0,len);
int progress=(int)((total+downloadlength)*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;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
int progress=values[0];
if (progress>lastProgress){
listener.onProgress(progress);
lastProgress=progress;
}
}
@Override
protected void onPostExecute(Integer status) {
super.onPostExecute(status);
switch (status){
case TYPE_SUCCESS:
listener.onSuccess();
break;
case TYPE_FAILED:
listener.onFailed();
break;
case TYPE_PAUSED:
listener.onPause();
break;
case TYPE_CANCELED:
listener.onCanceled();
break;
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;
}
}
修改mainactivity.javapackage com.example.xinwei.servicebestpractice;
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;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private DownloadService.DownloadBinder downloadBinder;
private ServiceConnection connection=new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
downloadBinder=(DownloadService.DownloadBinder)iBinder;
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startDownload=(Button)findViewById(R.id.start_download);
Button pauseDownload=(Button)findViewById(R.id.pause_download);
Button cancelDownload=(Button)findViewById(R.id.cancel_download);
startDownload.setOnClickListener(this);
pauseDownload.setOnClickListener(this);
cancelDownload.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)!=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_download:
String url="https://raw.githubusercontent.com/guolindev/eclipse/master/eclipse_inst-win64.exe";
downloadBinder.startDownload(url);
break;
case R.id.pause_download:
downloadBinder.pauseDownload();
break;
case R.id.cancel_download:
downloadBinder.cancelDownload();
break;
default:
break;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case 1:
if (grantResults.length>0&&grantResults[0]!= PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, "denied permission will not use program", Toast.LENGTH_SHORT).show();
finish();
}
break;
default:
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}
}
修改activity_main.xml<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.xinwei.servicebestpractice.MainActivity">
<Button
android:id="@+id/start_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="start download"/>
<Button
android:id="@+id/pause_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="pause download"/>
<Button
android:id="@+id/cancel_download"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="cancel download"/>
</LinearLayout>
在AndroidManifest.xml里manifest标签下添加<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
因为我这手机模拟器不太好使,内存卡出了点问题,所以就不演示了。 |