zoukankan      html  css  js  c++  java
  • Service实现文件下载

      首先在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);
            }
          }
        }

  • 相关阅读:
    洛谷P2580(trie)
    bzoj4373:算数天才与等差数列
    校门外的树(3)
    Ubuntu系统配置的一些要点
    字符串hash
    洛谷P3387 缩点模板
    3dmax多个版本软件的安装包以及安装教程
    【3dsmax2016】安装图文教程、破解注册以及切换语言方法
    photoshop常用快捷键大全
    unity3d脚本语言中的引用类型
  • 原文地址:https://www.cnblogs.com/zhanglei93/p/4714112.html
Copyright © 2011-2022 走看看