import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseBody;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
//图片的下载路径
private String path = “http://p3.so.qhmsg.com/t016f0540122dbc10c3.jpg”;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bitmap bitmap = (Bitmap) msg.obj;
//让进度条加载完成后自动消失
manager.cancel(3);
//为imageview设置图片资源
imageView.setImageBitmap(bitmap);
}
};
private Button button;
private ImageView imageView;
private NotificationManager manager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//查找控件
button = (Button) findViewById(R.id.btn);
imageView = (ImageView) findViewById(R.id.iview);
//创建notify管理者对象
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//button按钮的点击事件,当点击button按钮的时候进行进度条的显示,并下载图片
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//调用方法
init();
}
});
}
private void init() {
//创建notification builder 对象
final Notification.Builder mbuilder = new Notification.Builder(this);
//设置通知栏图标
mbuilder.setSmallIcon(android.R.mipmap.sym_def_app_icon);
//设置通知栏提示语
mbuilder.setContentText(“正在下载”);
//创建OkHttpClient对象
OkHttpClient client = new OkHttpClient();
//创建请求对象的建造者
final Request.Builder builder = new Request.Builder();
//添加下载路径
builder.url(path);
//通过建造者对象,创建请求对象
Request request = builder.build();
//创建call对象
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
//请求失败时调用的方法
public void onFailure(Request request, IOException e) {
}
@Override
//请求响应成功时调用的方法
public void onResponse(Response response) throws IOException {
//创建一个变量记录下载了的总的大小
int download = 0;
//获取响应对象
ResponseBody body = response.body();
//获取网络请求的最大值
int length = (int) body.contentLength();
//获取数据流
InputStream inputStream = body.byteStream();
//创建一个字节数组输出流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = 0;
byte[] bytes = new byte[1024];
while ((len = input
Stream.read(bytes)) != -1) {
download += len;
mbuilder.setProgress(100, ((int) download / length * 100), false);
manager.notify(3, mbuilder.build());
bos.write(bytes, 0, bytes.length);
bos.flush();
}
//将字节数组输出流转换成bitmap对象
mbuilder.setProgress(100, ((int) download / length * 100), false);
manager.notify(3, mbuilder.build());
bos.write(bytes, 0, bytes.length);
bos.flush();
}
//将字节数组输出流转换成bitmap对象