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. How can I style a JavaFX SplitMenuButton in CSS

    0 down vote favorite I try to style a SplitMenuButton in JavaFX. I've got a menuButton and a SplitMe ...

  2. centos下使用eclipse jlink 调试uboot

    一.安装java jdk 1.CentOS默认情况下,会安装OpenOffice之类的软件,这些软件需要Java的支持,默认会安装JDK的环境,若需要特定的Java环境,最好将默认的JDK彻底删除: ...

  3. jquery json ajax -2

    如果使用的是虚拟空间, 那么你不能操纵/配置服务器上的php.ini配置文件 但是可以在自己的php文件中, 通过ini_set(...), 和一些对应的函数, 去重置(临时的,仅在当前文件中生效的) ...

  4. Matlab之字符串处理

    Matlab处理字符串 1.取得部分字符串 我们有一个字符串 file='20131030_113109.TemporaryAlias.Poly5'; 简单操作举例: >> a=file( ...

  5. php面试题之三——PHP语言基础(基础部分)

    三.PHP语言基础 1. strlen( )与 mb_strlen( )的作用分别是什么(新浪网技术部) strlen和mb_strlen都是用于获取字符串长度. strlen只针对单字节编码字符,也 ...

  6. poj1611(感染病患者)

    The Suspects Time Limit: 1000MS   Memory Limit: 20000K Total Submissions: 24587   Accepted: 12046 De ...

  7. 记录:js删除数组中某一项或几项的几种方法

    1:js中的splice方法 splice(index,len,[item])    注释:该方法会改变原始数组. splice有3个参数,它也可以用来替换/删除/添加数组内某一个或者几个值 inde ...

  8. VMware的四种网络连接方式

    mkdir  /mn/cdrom mount /dev/cdrom /mnt/cdrom Bridge:这种方式最简单,直接将虚拟网卡桥接到一个物理网卡上面,和linux下一个网卡 绑定两个不同地址类 ...

  9. iOS 中constraint 不等于约束和低优先级约束使用的简单体会

    看了些文章发现,在使用constraint时,不等于约束往往是和低优先级约束成对使用的,这样才能实现他们的效果. 看看例子 下面是在3.5存屏幕下的效果 图1,竖屏,在满足>=50的前提下,可以 ...

  10. iOS7 中的新加入的下载类NSURLSession(随ios版本更新而更新)

    想详细的了解网络下载的相关知识,要仔细阅读URL Loading System Programming Guide 这里有篇好文章(http://www.shinobicontrols.com/blo ...