ANDROID_MARS学习笔记_S01原始版_021_MP3PLAYER001_下载mp3文件

一、简介

1.在onListItemClick()中new Intent,Intent以存储序列化后的mp2Info对象作为参数,启动serivce

2.DownloadService在onStartCommand()中通过intent 获取mp3info,开启新线程,利用HttpDownloader下载文件到sdcard

二、代码
1.xml
(1)AndroidManifest.xml

增加

1 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

 

2.java
(1)Mp3ListActivity.java

 1     @Override
 2     protected void onListItemClick(ListView l, View v, int position, long id) {
 3         //根据用户点击列表当中的位置来得到响应的Mp3Info对象
 4         Mp3Info info = infos.get(position);
 5         //生成Intent对象
 6         Intent intent = new Intent();
 7         //将Mp3Info对象存入到Intent对象当中
 8         intent.putExtra("mp3Info", info);
 9         intent.setClass(this, DownloadService.class);
10         //启动Service
11         startService(intent);
12         super.onListItemClick(l, v, position, id);
13     }

 

(2)DownloadService.java

 1 package tony.mp3player.service;
 2 
 3 import tony.download.HttpDownloader;
 4 import tony.model.Mp3Info;
 5 import android.app.Service;
 6 import android.content.Intent;
 7 import android.os.IBinder;
 8 
 9 public class DownloadService extends Service{
10 
11     @Override
12     public IBinder onBind(Intent intent) {
13         return null;
14     }
15     
16     //每次用户点击ListActivity当中的一个条目时,就会调用该方法
17     @Override
18     public int onStartCommand(Intent intent, int flags, int startId) {
19         //从Intent对象当中将Mp3Info对象取出
20         Mp3Info info = (Mp3Info) intent.getSerializableExtra("mp3Info");
21         //生成一个下载线程,并将Mp3Info对象作为参数传递到线程对象当中
22         DownloadThread thread = new DownloadThread(info);
23         //启动新线程
24         new Thread(thread).start();
25         return super.onStartCommand(intent, flags, startId);
26     }
27 
28     class DownloadThread implements Runnable {
29         private Mp3Info info;
30         
31         public DownloadThread(Mp3Info info) {
32             super();
33             this.info = info;
34         }
35 
36         @Override
37         public void run() {
38             //根据MP3文件的名字,生成下载地址
39             String urlStr = "http://192.168.1.104:8080/mp3/" + info.getMp3Name();
40             HttpDownloader downloader = new HttpDownloader();
41             int result = downloader.downFile(urlStr, "mp3", info.getMp3Name());
42             String msg = null;
43             switch (result) {
44             // -1:代表下载文件出错 0:代表下载文件成功 1:代表文件已经存在
45             case -1:
46                 msg = "下载失败";break;
47             case 0:
48                 msg = "文件下载成功";break;
49             case 1:
50                 msg = "文件已经存在,不需要重复下载";break;
51             }
52             //使用Notification提示客户下载结果
53         }
54         
55     }
56 }

 

你可能感兴趣的:(ANDROID_MARS学习笔记_S01原始版_021_MP3PLAYER001_下载mp3文件)