简单强大的下载类
每次打开应用,需要显示最新loading图,这个时候需要在后台默默的下载到本地,再次打开应用从本地取出显示
/**
* 下载类
*/
public class FileDownloadManager {
private static final int threadPoolNum = 5;
private Context mContext;
private static FileDownloadManager mInstance;
private Handler mHandler = new Handler();
private ExecutorService mService = Executors.newFixedThreadPool(threadPoolNum);
private Map<String, DownloadTask> downloadTask = new Hashtable<>();
private FileDownloadManager(Context context) {
this.mContext = context;
}
public static FileDownloadManager getInstance(Context context) {
synchronized (FileDownloadManager.class) {
if (mInstance == null) {
mInstance = new FileDownloadManager(context);
}
}
return mInstance;
}
public static FileDownloadManager getInstance() {
return mInstance;
}
private synchronized void fishedDownloadTask(String url) {
downloadTask.remove(url);
}
public synchronized void request(String url, DataListener<String> listener) {
String fileName = MiniFileManager.existFileForUrl(mContext, url);
if (fileName != null) {
listener.onResponse(fileName);
} else {
DownloadTask task = downloadTask.get(url);
if (task != null) {
task.addListener(listener);
} else {
DownloadTask loadTask = new DownloadTask(url, listener);
downloadTask.put(url, loadTask);
mService.execute(loadTask);
}
}
}
class DownloadTask implements Runnable {
private String address;
private List<DataListener<String>> listeners = new ArrayList<>();
private String fileName;
private String tmpFileName;
public DownloadTask(String url,DataListener<String> listener) {
this.address = url;
this.listeners.add(listener);
this.fileName = MiniFileManager.fileForUrl(mContext, address);
this.tmpFileName = this.fileName + "_tmp";
}
public void addListener(DataListener<String> listener) {
this.listeners.add(listener);
}
@Override
public void run() {
HttpURLConnection connection = null;
InputStream inputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try {
java.net.URL url = new java.net.URL(address);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
if (code == 200) {
MiniFileManager.createFile(this.tmpFileName);
bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(this.tmpFileName));
inputStream = connection.getInputStream();
byte[] cache = new byte[2048];
int len;
while ((len = inputStream.read(cache, 0, cache.length)) != -1) {
bufferedOutputStream.write(cache, 0, len);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
bufferedOutputStream = null;
inputStream.close();
inputStream = null;
MiniFileManager.rename(this.tmpFileName, fileName);
final String fname = fileName;
mHandler.post(new Runnable() {
@Override
public void run() {
for (DataListener listener : listeners) {
listener.onResponse(fname);
}
}
});
} else {
final String c = String.valueOf(code);
mHandler.post(new Runnable() {
@Override
public void run() {
//TODO
}
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bufferedOutputStream != null) {
bufferedOutputStream.close();
}
if (inputStream != null) {
inputStream.close();
}
if (connection != null) {
connection.disconnect();
}
}
catch (Exception e) {
}
fishedDownloadTask(address);
}
}
}
}
FileManager
/**
* File类
*/
public class MiniFileManager {
public static String existFileForUrl(Context context,String url){
String fileName = fileForUrl(context, url);
if (fileName != null){
File file = new File(fileName);
if (file.exists()){
return fileName;
}
}
return null;
}
public static String fileForUrl(Context context, String url) {
String fileName = MiniMd5.md5String(url);
int index = url.lastIndexOf(".");
if (index != -1) {
String ext = url.substring(index + 1);
fileName = fileName + "." + ext;
}
fileName = getAppFilePath(context, "cache/download") + File.separator + fileName;
return fileName;
}
private static String getAppFilePath(Context context, String directoryPath) {
String sdcardPath = getSdcardPath(context);
if (context != null) {
String path = sdcardPath + File.separator + MiniFramework.appShortName + File.separator + directoryPath;
File file = new File(path);
if (!file.exists() || !file.isDirectory()) {
file.mkdirs();
}
return path;
} else {
return sdcardPath;
}
}
private static String getSdcardPath(Context context) {
String sdcardPath;
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
sdcardPath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
} else {
sdcardPath = context.getCacheDir().getPath();
}
return sdcardPath;
}
public static void createFile(String tmpFileName) throws IOException {
File file = new File(tmpFileName);
if (file.exists()){
file.delete();
}
file.createNewFile();
}
public static void rename(String tmpFileName, String fileName) {
File file = new File(tmpFileName);
if (file.exists()){
File objectFile = new File(fileName);
if (objectFile.exists()){
objectFile.delete();
}
file.renameTo(objectFile);
}
}
}
public interface DataListener<T> {
void onResponse(T data);
}
首先你需要先在MainActivity中调用,获取最新loading图
public class MainActivity extends AppCompatActivity {
private String url = "http://img4.imgtn.bdimg.com/it/u=1740878494,1564612638&fm=21&gp=0.jpg";
public static final String SHOW_IMAGE = "showImage";
private ACache cache; //缓存,以键值对的形式存储。你也可以用SharedPreferences来代替
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initDownload();
}
/**
*下载最新图片,缓存到本地
*/
private void initDownload() {
cache = ACache.get(MainActivity.this);
FileDownloadManager.getInstance().request(url, new DataListener<String>() {
@Override
public void onResponse(String data) {
if (data != null) {
cache.put(MainActivity.SHOW_IMAGE, data);
}
}
});
}
}
LoadingActivity中显示下载好的图片
private void initShowImage() {
cache = ACache.get(this);
File file = null;
String imageData = cache.getAsString(MainActivity.SHOW_IMAGE);
if (imageData != null) {
file = new File(imageData);
}
if (imageData != null && file.exists()) {
ImageLoader.getInstance().displayImage("file://" + imageData, mLoadingImage);
} else {
assert mLoadingImage != null;
mLoadingImage.setImageResource(R.drawable.show_girl);
}
}