1.通过intentservies 下载图片到本地并把路劲存在sp中。
package hnq.intentservicetest;
import android.app.IntentService;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
/**
* Created by Administrator on 2017/6/21.
*/
public class MyIntentService extends IntentService {
private final String TAG="MyIntentService";
private String url ;//文件的网络地址
private String path ;//文件在本地的目录地址
private String name;//文件的名字
private String key;//文件路径存储在SP中的key
/**
* 构造方法 必须要
*/
public MyIntentService() {
//表示这个线程的名字 可随意
super("MyIntentService");
}
//会自动开启线程下载的
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
url = extras.getString("url");
path = extras.getString("path");
name=extras.getString("name");
key=extras.getString("key");
if (TextUtils.isEmpty(url)||TextUtils.isEmpty(path)||TextUtils.isEmpty(name)||TextUtils.isEmpty(key)){
Log.i(TAG,"url,path,name,key不能为空");
return;
}
//如果文件夹目录不存在则创建
File file = new File(path );
if (!file.exists())
file.mkdirs();
downloadFile(url,new File(path+name));
FileUtils.deleteFile(new File(path),new File(path+name));
}
/**
* 下载文件到本地文件的放法
* @param downloadUrl 网络地址
* @param file 本地文件目录
*/
private void downloadFile(String downloadUrl, File file) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
InputStream ips = null;
try {
URL url = new URL(downloadUrl);
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
huc.setRequestMethod("GET");
huc.setReadTimeout(10000);
huc.setConnectTimeout(3000);
ips = huc.getInputStream();
// 拿到服务器返回的响应码
int hand = huc.getResponseCode();
if (hand == 200) {
// 建立一个byte数组作为缓冲区,等下把读取到的数据储存在这个数组
byte[] buffer = new byte[8192];
int len = 0;
while ((len = ips.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
saveFileMsg(file);
} else {
Log.i(TAG,"网络连接失败");
}
} catch (ProtocolException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
if (ips != null) {
ips.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 保存文件路劲到sp中
* @param file
*/
private void saveFileMsg(File file){
if (file==null||!file.exists())
return;
SharedPreferences sharedPreferences=getSharedPreferences(TAG,0);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString(key,file.getAbsolutePath());
edit.commit();
}
}
2.文件util 包含,获取文件的md5值,为了和服务器对照保证文件的完整性以及验证服务器的最新的图片是否和本地相同。以及删除该目录下的其他文件,防止随时间的增加文件的数量过大。
package hnq.intentservicetest;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Administrator on 2017/6/21.
*/
public class FileUtils {
/**
* 获取文件的MD5值
* @param file
* @return
*/
public static String getMD5(File file){
if (!file.isFile()) {
return null;
}
MessageDigest digest = null;
FileInputStream in = null;
byte buffer[] = new byte[1024];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
}
/**
* 获取目录下的所有文件
* @param dir
* @return
*/
public static List<File> listFilesInDir(File dir) {
if (!dir.isDirectory()||!dir.exists()) return null;
List<File> list = new ArrayList<>();
File[] files = dir.listFiles();
if (files != null && files.length != 0) {
for (File file : files) {
list.add(file);
if (file.isDirectory()) {
List<File> fileList = listFilesInDir(file);
if (fileList != null) {
list.addAll(fileList);
}
}
}
}
return list;
}
/**
* 删除除file以外的同目录下的其他文件
* @param dir
* @param file
*/
public static void deleteFile(File dir,File file){
if (!file.exists()) return;
List<File> files = listFilesInDir(dir);
for (File file1 : files) {
String absolutePath = file1.getAbsolutePath();
Log.i("sss","delete"+absolutePath);
if (!file.getAbsolutePath().equals(absolutePath)){
file1.delete();
}
}
}
}
3.简单测试代码。
package hnq.intentservicetest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import java.io.File;
public class MainActivity extends AppCompatActivity {
Button btn001;
ImageView imageView001;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn001= (Button) findViewById(R.id.btn001);
imageView001= (ImageView) findViewById(R.id.image001);
btn001.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,MyIntentService.class);
Bundle bundle=new Bundle();
bundle.putString("url","https://www.baidu.com/img/bd_logo1.png");
bundle.putString("path",getFilesDir().getAbsolutePath()+"/image/");
bundle.putString("name","baidu.png");
bundle.putString("key","path");
intent.putExtras(bundle);
startService(intent);
}
});
SharedPreferences myIntentService = getSharedPreferences("MyIntentService", 0);
String path = myIntentService.getString("path", "");
if (!TextUtils.isEmpty(path)){
Log.i("sss",path);
String md5 = FileUtils.getMD5(new File(path));
Log.i("sss",md5);
Bitmap bitmap = BitmapFactory.decodeFile(path);
imageView001.setImageBitmap(bitmap);
}
}
}
4.其他工作
清单文件中加权限,注册服务。此处用app的私有目录,不用文件读写权限。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="hnq.intentservicetest">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<service android:name=".MyIntentService"></service>
</application>
</manifest>