首先创建一个Service ——下载进度
public class DownloadService extends Service {
private DownLoadTask downLoadTask;
private String downloadUrl;
private DownloadListener listener =new DownloadListener() {
@Override
public void onProgress(int progress) {
getNotificationManager().notify(1,getNotification("正在下载软件...",progress));
Toast.makeText(DownloadService.this, "Download Success", Toast.LENGTH_SHORT).show();
}
@Override
public void onSuccess() {
downLoadTask=null;
stopForeground(true);
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 onPaused() {
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();
}
};
private DownloadService.DownloadBinder mBinder =new DownloadService.DownloadBinder();
private NotificationCompat.Builder builder;
class DownloadBinder extends Binder {
public void startDownload(String url) {
if (downLoadTask == null) {
downloadUrl = url;
downLoadTask = new DownLoadTask(listener);
downLoadTask.execute(downloadUrl);
if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.O){
startForeground(1, getNotification("Downloading...", 0));
Toast.makeText(DownloadService.this, "Downing...", Toast.LENGTH_SHORT);
}
}
}
public void pauseDownload() {
if (downLoadTask != null) {
downLoadTask.pauseDownload();
}
}
public void cancelDownload() {
if (downLoadTask != null) {
downLoadTask.cancleDownload();
} 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, "Cancled", Toast.LENGTH_SHORT).show();
}
}
}
}
private NotificationManager getNotificationManager() {
return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private void updateNotification(int progress) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "default");
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("正在下载...");
builder.setContentText(progress + "%");
builder.setProgress(100, progress, false);
Notification notification = builder.build();
manager.notify(1, notification);
}
private Notification getNotification(String title, int progress) {
Intent intent = new Intent(this, DownloadActivity.class);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel("myid", "myname", NotificationManager.IMPORTANCE_HIGH);
manager.createNotificationChannel(channel);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE);
builder = new NotificationCompat.Builder(this,"myid");
builder.setSmallIcon(R.mipmap.home_kt);
builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.home_cf));
builder.setContentTitle(title);
builder.setContentIntent(pendingIntent);
builder.setChannelId("myid");
builder.setContentTitle("正在下载...");
builder.setContentText(progress + "%");
builder.setProgress(100, progress, false);
}
return builder.build();
}
}
DownloadActivity——调用
public class DownloadActivity 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 @SuppressLint("MissingInflatedId")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
Button startDownload = findViewById(R.id.start_download);
Button pause_download = findViewById(R.id.pause_download);
Button cancel_download = findViewById(R.id.cancel_download);
startDownload.setOnClickListener(this);
pause_download.setOnClickListener(this);
cancel_download.setOnClickListener(this);
Intent intent =new Intent(this, DownloadService.class);
startService(intent);
bindService(intent,connection,BIND_AUTO_CREATE);
if (ContextCompat.checkSelfPermission(DownloadActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(DownloadActivity.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,"权限被拒绝了呦",Toast.LENGTH_SHORT).show();
finish();
}
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}
}
DownLoadTask ——下载任务
public class DownLoadTask extends AsyncTask<String, Integer, Integer> {
public static final int TYPE_SUCCESS = 0;
public static final int TYPE_FAIL = 2;
public static final int TYPE_PAUSED = 3;
public static final int TYPE_CANCLE = 4;
private DownloadListener listener;
private boolean isCanceled = false;
private boolean isPaused = false;
private int lastProgress;
public DownLoadTask(DownloadListener downloadListener) {
listener = downloadListener;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Integer doInBackground(String... params) {
InputStream inputStream = null;
RandomAccessFile saveFile = null;
File file = null;
try {
long downLoadLenght = 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()) {
downLoadLenght = file.length();
}
long contentLenght = getContentLenght(downloadUrl);
if (contentLenght == 0) {
return TYPE_FAIL;
} else if (contentLenght == downLoadLenght) {
return TYPE_SUCCESS;
}
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.addHeader("RANGE", "bytes=" + downLoadLenght + "-")
.url(downloadUrl)
.build();
Response response = client.newCall(request).execute();
if (response != null) {
inputStream = response.body().byteStream();
saveFile = new RandomAccessFile(file, "rw");
saveFile.seek(downLoadLenght);
}
byte[] b = new byte[1024];
int total = 0;
int len;
while ((len = inputStream.read(b)) != -1) {
if (isCanceled) {
return TYPE_CANCLE;
} else if (isPaused) {
return TYPE_PAUSED;
} else {
total += len;
saveFile.write(b, 0, len);
int progress = (int) ((total + downLoadLenght) * 100 / contentLenght);
publishProgress(progress);
}
}
response.body().close();
return TYPE_SUCCESS;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (saveFile != null) {
saveFile.close();
}
if (isCanceled && file != null) {
file.delete();
}
} catch (Exception e) {
}
}
return TYPE_FAIL;
}
private long getContentLenght(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 contentLenght = response.body().contentLength();
response.close();
return contentLenght;
}
return 0;
}
@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 integer) {
switch (integer) {
case TYPE_CANCLE:
listener.onCanceled();
break;
case TYPE_SUCCESS:
listener.onSuccess();
break;
case TYPE_PAUSED:
listener.onPaused();
break;
case TYPE_FAIL:
listener.onFailed();
break;
}
}
public void pauseDownload(){
isPaused =true;
}
public void cancleDownload(){
isCanceled =true;
}
}
资源文件权限
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
文章评论