public class SecondActivity extends AppCompatActivity {
private SeekBar seekbar;
private TextView tv;
private ImageView iv;
private LinearLayout ll;
private String url="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1502292182115&di=d114cc30ec7af897ade267f920b185c3&imgtype=0&src=http%3A%2F%2Fpic41.nipic.com%2F20140521%2F18810499_233252246000_2.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
initView();
initData();
new MyAsynTaske().execute(url);
}
private void initData() {
seekbar.setMax(100);
}
private void initView() {
seekbar = (SeekBar) findViewById(R.id.seekbar);
tv = (TextView) findViewById(R.id.tv);
iv = (ImageView) findViewById(R.id.iv);
ll = (LinearLayout) findViewById(R.id.ll);
}
/**
* 创建MyAsyncTask类
*/
class MyAsynTaske extends AsyncTask<String,Integer,Bitmap>{
/**
* 请求之前调用的方法 用于处理请求之前的逻辑(主线程)
*/
protected void onPrExecute(){
ll.setVisibility(View.VISIBLE);
}
/**
* 请求网络调用的方法(子线程)
* @param strings
* @return
*/
@Override
protected Bitmap doInBackground(String... strings) {
try {
URL url=new URL(strings[0]);
HttpURLConnection connection= (HttpURLConnection) url.openConnection();
connection.connect();
//获取返回的数据的总字节长度
int totalLength = connection.getContentLength();
//声明当前的字节长度
int currLength=0;
//转换成百分比
int progress=0;
if(200==connection.getResponseCode()){
InputStream in = connection.getInputStream();
ByteArrayOutputStream baos=new ByteArrayOutputStream();
int len=0;
byte[] buffer=new byte[10];
while((len=in.read(buffer))!=-1)
{
//获取当前进度
currLength+=len;
//进度转换为百分比
progress= (int) ((float)currLength/totalLength*100);
System.out.println("progress=========="+progress);
publishProgress(progress);
baos.write(buffer,0,len);
}
return BitmapFactory.decodeByteArray(baos.toByteArray(),0,baos.size());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 请求过程中,进度条的更新(主线程)
*
*/
@Override
protected void onProgressUpdate(Integer... values) {
seekbar.setProgress(values[0]);
tv.setText(values[0]+"%");
}
/**
* 请求结束后调用的方法 用于更新UI(主线程)
*/
protected void onPostExecute(Bitmap bitmap){
iv.setImageBitmap(bitmap);
ll.setVisibility(View.GONE);
}
}
}
通过AsyncTask异步获取网络图片
最新推荐文章于 2018-05-29 08:49:00 发布