介绍:
M:model 模型 业务处理
V:view 视图 UI
C:Controller 控制层 控件监听
优点:
耦合性低,降低代码间的相互影响。
模块区域分明,利于维护。
代码
model类:
提供一个方法,传需要用的参数
package com.example.day2lx.model;
public interface DownLoadImageModel {
void DownLoadImage(String url,String path,DownLoadImageListener downLoadImageListener);
}
Listener类:
写回调方法
package com.example.day2lx.model;
public interface DownLoadImageListener {
void setMax(int max);
void setProgress(int progress);
void finish();
}
实现类:
写耗时操作,可以写个子线程
package com.example.day2lx.model;
import com.example.day2lx.thread.DownLoadImageThread;
public class DownLoadImageimpl implements DownLoadImageModel{
@Override
public void DownLoadImage(String url, String path, DownLoadImageListener downLoadImageListener) {
new DownLoadImageThread(url,path,downLoadImageListener).start();
}
}
Thread:
package com.example.day2lx.thread;
import android.util.Log;
import com.example.day2lx.model.DownLoadImageListener;
import com.example.day2lx.model.DownLoadMp3Listener;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownLoadImageThread extends Thread{
String url;
String path;//路径
DownLoadImageListener downLoadImageListener;
public DownLoadImageThread(String url, String path, DownLoadImageListener downLoadImageListener) {
this.url = url;
this.path = path;
this.downLoadImageListener =downLoadImageListener;
}
@Override
public void run() {
Log.i("TAG", "进入子线程");
try {
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();
Log.i("TAG", "run: 连接");
Log.i("TAG", "run: 连接 - 相应码 "+connection.getResponseCode());
if (connection.getResponseCode()==200) {
int max = connection.getContentLength();
downLoadImageListener.setMax(max);
Log.i("TAG", "发送最大值:"+max);
InputStream is = connection.getInputStream();
int len=0;
byte[] bys = new byte[1024];
FileOutputStream fos = new FileOutputStream(path);
int count=0;
while ((len=is.read(bys))!=-1) {
fos.write(bys,0,len);
count+=len;
downLoadImageListener.setProgress(count);
Log.i("TAG", "不断发送count:"+count);
if (count==len) {
Log.i("TAG", "下载成功");
downLoadImageListener.finish();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
在MAinActivity中:
//声明
DownLoadImageModel downLoadImageModel;
downLoadImageModel=new DownLoadImageimpl();
downLoadImageModel.DownLoadImage("http://172.20.10.4/yu_hfs/a.png", "/sdcard/Pictures/xiazai2.png", new DownLoadImageListener() {
@Override
public void setMax(final int max) {
runOnUiThread(new Runnable() {
@Override
public void run() {
seekBar.setMax(max);
}
});
}
@Override
public void setProgress(final int progress) {
runOnUiThread(new Runnable() {
@Override
public void run() {
seekBar.setProgress(progress);
}
});
}
@Override
public void finish() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_SHORT).show();
}
});
}
});