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. fatl exception occurred异常/错误的一种可能情况

    如果,有可能是 java.lang.ClassLoader类内部出错,请自行检查

  2. 转:Java NIO系列教程(八) DatagramChannel

    Java NIO中的DatagramChannel是一个能收发UDP包的通道.因为UDP是无连接的网络协议,所以不能像其它通道那样读取和写入.它发送和接收的是数据包. 打开 DatagramChann ...

  3. linux读写ntfs

    frankly speaking, i hope to get a higher salary. yours frankly= yours sincerely = sincerely yours =y ...

  4. wordpress编辑主题时报错Warning: scandir() has been disabled for security reasons in

    在ubuntu下面安装了一个wordpress程序,在后台什么都没干,编辑主题时,发现页面中报下面的错误. notice: /home/wwwroot/test.localhost/wordpress ...

  5. 避免使用CSS表达式

    http://www.cnblogs.com/chenxizhang/archive/2013/05/01/3053439.html 这一篇我来和大家讨论个原则:Avoid CSS Expressio ...

  6. HDU 1018 Big Number (数学题)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1018 解题报告:输入一个n,求n!有多少位. 首先任意一个数 x 的位数 = (int)log10(x ...

  7. [Effective JavaScript 笔记] 第14条:当心命名函数表达式笨拙的作用域

    js函数会根据上下文改变其含义. function double(x){return x*2;} 这是一个函数声明,也可以是一个命名函数表达式(named function expression),取 ...

  8. Opencv Cookbook阅读笔记(四):用直方图统计像素

    灰度直方图的定义 灰度直方图是灰度级的函数,描述图像中该灰度级的像素个数(或该灰度级像素出现的频率):其横坐标是灰度级,纵坐标表示图像中该灰度级出现的个数(频率). #include <open ...

  9. poj1125最短路

    Stockbroker Grapevine Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 30408   Accepted: ...

  10. 1-2+3-4+5-6+7......+n的几种实现

    本文的内容本身来自一个名校计算机生的一次面试经历,呵呵,没错,你猜对了,肯定 不是我 个人很喜欢这两道题,可能题目原本不止两道,当然,我这里这分析我很喜欢的两道. 1.写一个函数计算当参数为n(n很大 ...