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. java.lang.NoClassDefFoundError: org/hibernate/cfg/Configuration解决方法

    Autowiring of fields failed; nested exception is...........Error creating bean with name 'siteOperat ...

  2. Linux系统日志及日志分析

    Linux系统日志及日志分析   Linux系统拥有非常灵活和强大的日志功能,可以保存几乎所有的操作记录,并可以从中检索出我们需要的信息. 大部分Linux发行版默认的日志守护进程为 syslog,位 ...

  3. motto7

    与其羡慕别人,还不如模仿别人的过程.

  4. MapReduce使用JobControl管理实例

    import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.fs.Path; impo ...

  5. CSS2-3常见的demo列子总结

    CSS2-3常见的demo列子总结 阅读目录 1. css超过一行或者多行后显示省略号. 2. css图片未知高度垂直居中完美解决方案. 3. 学习使用 :before和 :after伪元素 回到顶部 ...

  6. Matlab图像处理入门

    1. Matlab基础 1.1     数据格式 Matlab默认的数据格式为双精度浮点数的矩阵或数组,同时支持其它数据类型.Matlab将单变量看作1´1的数组.Matlab支持的数据类型如下: 索 ...

  7. [POJ1003]Hangover

    [POJ1003]Hangover 试题描述 How far can you make a stack of cards overhang a table? If you have one card, ...

  8. [转载]WiFi有死角? 巧用旧无线路由器扩展覆盖

    怎么了,家里的WiFi有死角?老旧无线路由器的无线覆盖不给力?现在大功率无线产品或双频无线产品的售价并不便宜,而且仅靠一台无线路由器并不能满足多户型家庭的无线覆盖需求.那么,是不是有什么廉价而又实用的 ...

  9. c++ exports def文件

    https://msdn.microsoft.com/zh-cn/library/hyx1zcd3(v=vs.80).aspx EXPORTS 引入了一个由一个或多个 definitions(导出的函 ...

  10. 【Python】python代码如何调试?

    Python 程序如何高效地调试? 现在我在debug python程序就只是简单在有可能错误的地方print出来看一下,不知道python有没像c++的一些IDE一样有单步调试这类的工具?或者说各位 ...