【练习】使用服务下载图片并保存到sdcard
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的更多相关文章
- 使用官方组件下载图片,保存到MySQL数据库,保存到MongoDB数据库
需要学习的地方,使用官方组件下载图片的用法,保存item到MySQL数据库 需要提前创建好MySQL数据库,根据item.py文件中的字段信息创建相应的数据表 1.items.py文件 from sc ...
- Unity WWW下载图片并保存到Unity的Assets下
1.新建一个UGUI的Image. 2.新建一个脚本wwwTest.cs: using System.Collections; using System.Collections.Generic; us ...
- android如何保存读取读取文件文件保存到SDcard
android如何保存读取读取文件文件保存到SDcard 本文来源于www.ifyao.com禁止转载!www.ifyao.com 上图为保存文件的方法体. 上图为如何调用方法体保存数据. 上面的截图 ...
- Appengine直接下载文件并保存到google drive
一直对下载文件比较感兴趣.前些日子无意搜到google 推出一项服务,可以直接将文件下载到google drive中,原型猛戳这里,但有限额限制.一时脑洞大开,可不可以在appengine 上架设服务 ...
- PHP远程下载图片,微信头像存到本地,本地图片转base64
方法一(推荐): function download_remote_pic($url){ $header = [ 'User-Agent: Mozilla/5.0 (Windows NT 6.1; W ...
- word文档的图片怎么保存到ueditor上
word图片转存,是指UEditor为了解决用户从word中复制了一篇图文混排的文章粘贴到编辑器之后,word文章中的图片数据无法显示在编辑器中,也无法提交到服务器上的问题而开发的一个操作简便的图片转 ...
- 自动网页截图并指定元素位置裁剪图片并保存到excel表格
# coding=utf-8 import os import time from selenium import webdriver from selenium.webdriver.chrome.o ...
- asp.net c#整理所有本地的图片一次性保存到SQL表中
string sql1 = "select distinct tx from tiku where tx is not null"; //检索tx表中所有的不重复的tx值 stri ...
- 从网络上获取图片并保存在sdCard上
package com.aib.soft; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileO ...
随机推荐
- C++中的异常处理(二)
C++中的异常处理(二) 标签: c++C++异常处理 2012-11-24 20:56 1713人阅读 评论(2) 收藏 举报 分类: C++编程语言(24) 版权声明:本文为博主原创文章,未经 ...
- Matlab的曲线拟合工具箱CFtool使用简介
http://phylab.fudan.edu.cn/doku.php?id=howtos:matlab:mt1-5 一. 单一变量的曲线逼近Matlab有一个功能强大的曲线拟合工具箱 cftool ...
- Ubuntu下编译SuiteSparse-4.4.1和METIS-4.0.3
网上关于编译的介绍非常多,其实ubuntu系统自带编译好的SuiteSparse,不想折腾的话,用新立得很容易就搞定 准备工作: 下载并编译OpenBLAS(会连带Lapack也下载和编译),图省事请 ...
- Song Jiang's rank list
Song Jiang's rank list Time Limit:1000MS Memory Limit:512000KB 64bit IO Format:%I64d & ...
- Python 常用函数大体分类
==================系统库函数================ 字符串函数 举例数学函数 import math val=math.sin(3.14/6) val=math.sin(m ...
- RHEL6.2下挂载光驱安装软件
导读 在RHEL6.2命令行模式下挂载虚拟光驱安装软件也许会难倒许多新手,下面我给大家详细介绍一下.首先说明一下,本教程是以RHEL6.2版本下安装Apache为例.主要讲述挂载虚拟光驱的方法.环境: ...
- HDU 1176免费馅饼 DP数塔问题转化
L - 免费馅饼 Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u Submit Sta ...
- 数学复习 ---- Mathematics Notes: A Programmer's Perspective ---- by Orzer ---- 我是沙茶
今年是好没长进的一年呢..只学了些基本的方法.. 本文记号0] x:p x类型为p1] f(x) 表示一个函数2] (n_1,n_2,...) 表示多元组,特别的,(n)表示一个一元组3] x 表示一 ...
- Resumable Media Uploads in the Google Data Protocol
Eric Bidelman, Google Apps APIs team February 2010 Introduction The Resumable Protocol Initiating a ...
- First Position of Target
For a given sorted array (ascending order) and a target number, find the first index of this number ...