https://blog.csdn.net/lxsjt/article/details/52053748 参考
问题, 当一个类A 里正在下载 数据 ,有下载进度值,
在类B中 要得到 A 中的 进度值,又隐藏了 A 的一堆方法呢
解决: 此时就需要 一个接口来完成 他们之间数据的传输了
共需三部
1.先定义一个接口
package com.myxiaoqu.downlist.douyin;
public interface DouYinSeekBar_Interface {
/*
https://blog.csdn.net/wbw1985/article/details/5912341
*/
/***
* 进度值
* @param progress
*/
void getprogressBar(int progress);
}
2 在 定义 需要 生成 进度值得类
类里面需要加入 2句
-
在 取值得方法里加上public DouYinSeekBar_Interface douYinSeekBar_interface;
-
这样值就 和接口搭上了douYinSeekBar_interface.getprogressBar(percent);
package com.myxiaoqu.downlist.douyin;
import com.myxiaoqu.bean.PathDaQuan;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownDouYinShuiYin {
public DouYinSeekBar_Interface douYinSeekBar_interface;
String path= PathDaQuan.filepath_douyinShuiYin;
public static void main(String[] args) {
public void testdown(String path, String httpurl) {
File file = new File(path);
String finalHttpurl = httpurl;
new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(finalHttpurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream in = conn.getInputStream();
int fileLength =conn.getContentLength();
byte buffer[] = new byte[102400];//这里是数据缓冲区,只能大不能小,尽可能够用
ByteArrayOutputStream bout = new ByteArrayOutputStream();
FileOutputStream out = new FileOutputStream(file);
int len = 0;
int count=0 ;
System.out.println("开始下载" );
while ((len = in.read(buffer)) > -1) {
bout.write(buffer, 0, len);
count=count+len;
// int progress = (int) (sum * 1.0f / total * 100);
int percent=count*100/fileLength;
douYinSeekBar_interface.getprogressBar(percent);
// System.out.println("percent "+percent);
System.out.println("下载进度 "+ percent+"/100");
//这里的percent可以直接拿走作为界面交互的参数,下载百分比
}
bout.flush();
out.write(bout.toByteArray());
bout.close();
in.close();
out.close();
System.out.println(" 下载结束" );
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
3 再 写一个 类, 里面 需要 获取 这个 不断变化进度值
public void button6_douyin_down(View view) {
DownDouYinShuiYin douYinShuiYin= new DownDouYinShuiYin() ;
String path= PathDaQuan.filepath_douyinShuiYin;
douYinShuiYin.testdown(path,tempPath);
// 就这一句 就能 接通 两个类 传数据了
douYinShuiYin.douYinSeekBar_interface= new DouYinSeekBar_Interface() {
@Override
public void getprogressBar(int progress) {
System.out.println("progress" + progress);
}
};
}