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);
            }
          }
        }

  • 相关阅读:
    存储那些事儿(二): 下一代Linux文件系统BTRFS简介
    RabbitMQ消息队列的小伙伴: ProtoBuf(Google Protocol Buffer)
    RabbitMQ消息队列(七):适用于云计算集群的远程调用(RPC)
    RabbitMQ消息队列(六):使用主题进行消息分发
    C++内存管理之shared_ptr
    C++程序调试方式总结
    匿名对象?临时对象?
    C++多态中虚函数表合并与继承问题
    C++继承体系中的内存分段
    C++继承体系中的内存对齐
  • 原文地址:https://www.cnblogs.com/zhanglei93/p/4714112.html
Copyright © 2011-2022 走看看