首先在Activity中声明Intent对象,启动Service:
//生成Intent对象
Intent intent = new Intent();
//将文件名对象存入到intent对象当中
intent.putExtra("name", filename);
intent.setClass(this, DownloadService.class);
//启动Service
startService(intent);
DownloadService定义如下:
public class DownloadService extends Service{
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
//每次用户点击ListActivity当中的一个条目时,就会调用该方法
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//从intent对象中将文件名取出
String name = intent.getExtra("name");
//生成一个下载线程,并将文件名对象作为参数传递到线程对象当中
DownloadThread downloadThread = new DownloadThread(name);
//启动新线程
Thread thread = new Thread(downloadThread);
thread.start();
return super.onStartCommand(intent, flags, startId);
}
class DownloadThread implements Runnable{
private String name = null;
public DownloadThread(String name){
this.name = name;
}
@Override
public void run() {
//下载地址是http://192.168.1.105:8080/mp3/forever.mp3
//根据MP3文件的名字生成下载地址
String fileUrl = "http://192.168.1.105:8080/mp3/" + name;
//生成下载文件所用的对象
HttpDownloader httpDownloader = new HttpDownloader(); //此类的定义见上一节文件下载和存入SD卡
//将文件下载并存储到SDCard当中
int fileresult = httpDownloader.downFile(fileUrl, "/mp3", name);
String resultMessage = null;
if(fileresult == -1){
resultMessage = "下载失败";
}
else if(fileresult == 0){
resultMessage = "文件已经存在,不需要重复下载";
}
else if(fileresult == 1){
resultMessage = "文件下载成功";
}
//使用Notifications提示客户下载结果
System.out.println(resultMessage);
}
}
}