1.创建请求request
Request request = new Request .Builder().url(url).build();
2.获取response,由于是耗时操作,所以需要异步获取
new Thread(new Runnable() {
@Override
public void run() {
...
try {
Response response = okHttpClient.newCall(request).execute();
if (!response.isSuccessful() || response == null || response.body() == null) {
sendMessage(1 , 0 , 0 , "" );
} else {
//处理response
...
}
} catch (IOException e) {
e.printStackTrace();
sendMessage(1 , 0 , 0 , "" );
}
}
}).start();
3.处理获取的response,并进行进度监听
InputStream is = null ;
byte [] buf = new byte [2048 ];
int len = 0 ;
FileOutputStream fos = null ;
try {
is = response.body ().byteStream();
int last = 0 ;
final long total = response.body ().contentLength();
long sum = 0 ;
fos = new FileOutputStream(new File(apkPath));
while ((len = is .read(buf)) != -1 ) {
sum += len;
fos.write(buf, 0 , len);
int now = (int ) (sum * 100 / total);
if (last < now) {
LogUtils.d("current:" + last + ";total:" + 100 );
sendMessage(3 , last, 100 , "" );
last = now;
}
}
fos.flush();
sendMessage(2 , 0 , 0 , "" );
} catch (IOException e) {
e.printStackTrace();
sendMessage(1 , 0 , 0 , "" );
} finally {
try {
if (is != null ) {
is .close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fos != null ) {
fos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
4.通知主线程进行相应的处理
public void sendMessage(int what, long current, long total, String msg) {
Message message = Message.obtain();
message.what = what;
message.arg1 = (int) current;
message.arg2 = (int) total;
message.obj = msg;
handler.sendMessage(message);
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1 :
//下载失败
...
break ;
case 2 :
//下载成功
...
break ;
case 3 :
//下载进度
int current = msg.arg1;
int total = msg.arg2;
...
break ;
}
}
};