点击下载按钮 下载音乐的Service extends IntentService{

  IntentService是继承于Service并处理异步请求的一个类,在IntentService内有一个工作线程来处理耗时操作,启动IntentService的方式和启动传统Service一样,同时,当任务执行完后,IntentService会自动停止,而不需要我们去手动控制。另外,可以启动IntentService多次,而每一个耗时操作会以工作队列的方式在IntentService的onHandleIntent回调方法中执行,并且,每次只会执行一个工作线程,执行完第一个再执行第二个,以此类推。

而且,所有请求都在一个单线程中,不会阻塞应用程序的主线程(UI Thread),同一时间只处理一个请求。

------------------------------------------------------------------------------------------
public class DownloadService extends IntentService{

private static final int NOTIFICATION_ID = 1000;

public DownloadService() {
super("download");
}
public DownloadService(String name) {
super(name);
}

/**
* 该方法中的内容将会在工作线程中执行
* 当轮到执行该消息时,将会运行onHandleIntent方法中的代码
*/
protected void onHandleIntent(Intent intent) {
//获取Acitvity传来的参数
String path=intent.getStringExtra("path");
int version=intent.getIntExtra("version", 0);
String title=intent.getStringExtra("title");
String total=intent.getStringExtra("total");
//执行下载操作  发送http请求
try {
//获取保存目录  /mnt/sdcard/Music/_128/title.mp3
File targetFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC), "_"+version+"/"+title+".mp3");
//判断父目录是否存在
if(!targetFile.getParentFile().exists()){
targetFile.getParentFile().mkdirs();
}
FileOutputStream fos = new FileOutputStream(targetFile);
//执行下载
//发送通知提示
sendNotification("音乐开始下载...", "音乐下载", "音乐准备下载...");
InputStream is = HttpUtils.getInputStream(path);
//边读边保存到sd卡
byte[] buffer=new byte[1024*200];
int length=0;
//保存当前已经读取了多少
int current=0;
//一共字节
int totalSize=Integer.parseInt(total);
while((length=is.read(buffer)) != -1){
fos.write(buffer, 0, length);
fos.flush();
current+=length;
//写入文件完毕后 发送通知提示进度
double progress = Math.floor(current*100.0/totalSize);
sendNotification("音乐开始下载...", "音乐下载", "下载进度:"+progress+"%");
}
fos.close();
clearNotification();
sendNotification("音乐下载完成", "音乐下载完成", "音乐下载完成");
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 清除通知
*/
public void clearNotification(){
//1.   NotificationManager
NotificationManager manager =(NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
manager.cancel(NOTIFICATION_ID);
}
/**
* 发送通知
* @param ticker
* @param title
* @param text
*/
public void sendNotification(String ticker, String title, String text){
//1.   NotificationManager
NotificationManager manager =(NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
//2.  Builder
Notification.Builder builder = new Notification.Builder(this);
builder.setTicker(ticker)
.setContentTitle(title)
.setContentText(text)
.setSmallIcon(R.drawable.ic_launcher);
Notification n=builder.build();
//3.  notify()
manager.notify(NOTIFICATION_ID, n);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值