public class StringUtils {
    public static String getStr(String path){
        String[] strs = path.split("/");
        return strs[strs.length-1];
    }
}
public class SdCardUtils {
    public static void saveDataToSdcard(byte[] data,String filename){
        File file = Environment.getExternalStorageDirectory();
        Log.i("Mian",file.getAbsolutePath());
        File file2 = new File(file,filename);
        try {
            FileOutputStream fos = new FileOutputStream(file2);
            fos.write(data);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
public class MainActivity extends AppCompatActivity {

    private ImageView imageView;
    private Intent intent ;
    private String path = "http://www.baidu.com/img/bdlogo.gif";
    private String filename;
    private String bitmap_path;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.image);
        filename = StringUtils.getStr(path);
        bitmap_path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+filename;
    }

    public void download(View view){
        intent = new Intent(this,MyService.class);
        intent.putExtra("key",path);
        startService(intent);
    }

    public void see(View view){
        Bitmap bitmap = BitmapFactory.decodeFile(bitmap_path);
        if(bitmap!=null){
            imageView.setImageBitmap(bitmap);
        }
    }
}
public class MyService extends Service {

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        final String path = intent.getStringExtra("key");

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        InputStream is = conn.getInputStream();
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024 * 2];
                        int ret;
                        while ((ret = is.read(buffer)) > 0) {
                            baos.write(buffer, 0, ret);
                        }
                        //保存到内存卡
                        SdCardUtils.saveDataToSdcard(baos.toByteArray(), StringUtils.getStr(path));
                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

* 图片下载完成后增加通知

优化MyService类

public class MyService extends Service {

    private NotificationManager manager;
    private NotificationCompat.Builder builder;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        manager = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
        builder = new NotificationCompat.Builder(getApplicationContext());
        builder.setAutoCancel(true);
        builder.setContentText("下载完成");
        builder.setContentTitle("通知");
        builder.setSmallIcon(R.mipmap.ic_launcher);
        Intent intent = new Intent(this,MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),0,intent,PendingIntent.FLAG_ONE_SHOT);
        builder.setContentIntent(pendingIntent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        final String path = intent.getStringExtra("key");

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL(path);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    int code = conn.getResponseCode();
                    if (code == 200) {
                        InputStream is = conn.getInputStream();
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024 * 2];
                        int ret;
                        while ((ret = is.read(buffer)) > 0) {
                            baos.write(buffer, 0, ret);
                        }
                        //保存到内存卡
                        SdCardUtils.saveDataToSdcard(baos.toByteArray(), StringUtils.getStr(path));
                        manager.notify(1,builder.build());
                    }

                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}

【练习】使用服务下载图片并保存到sdcard的更多相关文章

  1. 使用官方组件下载图片,保存到MySQL数据库,保存到MongoDB数据库

    需要学习的地方,使用官方组件下载图片的用法,保存item到MySQL数据库 需要提前创建好MySQL数据库,根据item.py文件中的字段信息创建相应的数据表 1.items.py文件 from sc ...

  2. Unity WWW下载图片并保存到Unity的Assets下

    1.新建一个UGUI的Image. 2.新建一个脚本wwwTest.cs: using System.Collections; using System.Collections.Generic; us ...

  3. android如何保存读取读取文件文件保存到SDcard

    android如何保存读取读取文件文件保存到SDcard 本文来源于www.ifyao.com禁止转载!www.ifyao.com 上图为保存文件的方法体. 上图为如何调用方法体保存数据. 上面的截图 ...

  4. Appengine直接下载文件并保存到google drive

    一直对下载文件比较感兴趣.前些日子无意搜到google 推出一项服务,可以直接将文件下载到google drive中,原型猛戳这里,但有限额限制.一时脑洞大开,可不可以在appengine 上架设服务 ...

  5. PHP远程下载图片,微信头像存到本地,本地图片转base64

    方法一(推荐): function download_remote_pic($url){ $header = [ 'User-Agent: Mozilla/5.0 (Windows NT 6.1; W ...

  6. word文档的图片怎么保存到ueditor上

    word图片转存,是指UEditor为了解决用户从word中复制了一篇图文混排的文章粘贴到编辑器之后,word文章中的图片数据无法显示在编辑器中,也无法提交到服务器上的问题而开发的一个操作简便的图片转 ...

  7. 自动网页截图并指定元素位置裁剪图片并保存到excel表格

    # coding=utf-8 import os import time from selenium import webdriver from selenium.webdriver.chrome.o ...

  8. asp.net c#整理所有本地的图片一次性保存到SQL表中

    string sql1 = "select distinct tx from tiku where tx is not null"; //检索tx表中所有的不重复的tx值 stri ...

  9. 从网络上获取图片并保存在sdCard上

    package com.aib.soft; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileO ...

随机推荐

  1. Office Web Apps资源

    http://www.cnblogs.com/poissonnotes/p/3277280.html#!comments http://www.cnblogs.com/poissonnotes/p/3 ...

  2. 复制”链接文件“到虚拟机(VirtualBox)的”共享文件夹“时报错:创建符号链接时报错:只读文件系统

    问题描述: 1.Ubuntu 中的 /www/目录,是宿主主机 Windows 7 以“共享文件夹”的形式挂载的: 2./etc/php.ini 是 /opt/software/php/etc/php ...

  3. [Effective JavaScript 笔记]第24条:使用变量保存arguments对象

    迭代器(iterator)是一个可以顺序存取数据集合的对象.其一个典型的API是next方法.该方法获得序列中的下一个值. 迭代器示例 题目:希望编写一个便利的函数,它可以接收任意数量的参数,并为这些 ...

  4. openCV的基本操作

    http://www.cnblogs.com/luluathena/archive/2010/09/29/1838471.html

  5. 最近win7更新后出现第二次打开IDE(delphi2007)的时候提示无法打开"EditorLineEnds.ttr"这个文件

    kb2982791 - 2014年8月12日更新 - http://support.microsoft.com/kb/2982791kb2970228 - 2014年8月12日更新 - http:// ...

  6. LVM XFS增加硬盘分区容量(resize2fs: Bad magic number in super-block while)

    LVM XFS增加硬盘分区容量(resize2fs: Bad magic number -- :: 分类: Linux LVM XFS增加硬盘分区容量(resize2fs: Bad magic num ...

  7. 【SpringMVC】SpringMVC系列7之POJO 对象绑定请求参数值

      7.POJO 对象绑定请求参数值 7.1.概述 Spring MVC 会按请求参数名和 POJO 属性名进行自动匹配,自动为该对象填充属性值.而且支持级联属性.如:dept.deptId.dept ...

  8. 追溯ASP.NET发展史

    2000年全新平台的ASP.NET 1.0正式发布,发展速度异常惊人,2003年升级为1.1版本.ASP.NET 1.1发布之后,更加激发了Web应用程序开发人员对ASP.NET的兴趣,并且对网络技术 ...

  9. Django中如何查找模板

    参考:http://my.oschina.net/zuoan001/blog/188782 Django的setting中有关找模板的配置有如下两个: TEMPLATE_LOADERS TEMPLAT ...

  10. poj1185

    状态压缩dp #include <cstdio> #include <cstring> #include <cstdlib> #include <iostre ...