package com.example.lenovo.linkai20170815; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class MainActivity extends AppCompatActivity { private String url="http://pic39.nipic.com/20140226/18071023_154707834000_2.jpg"; private LinearLayout lt; private TextView tv_progress; private ProgressBar pg_bar; private ImageView iv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); new MyAsync().execute(url); } private void initView() { tv_progress = (TextView) findViewById(R.id.tv_progress); lt = (LinearLayout) findViewById(R.id.lt); pg_bar = (ProgressBar) findViewById(R.id.pg_bar); iv = (ImageView) findViewById(R.id.iv); } class MyAsync extends AsyncTask<String,Integer,Bitmap> { @Override protected void onPreExecute() { lt.setVisibility(View.VISIBLE); } @Override protected Bitmap doInBackground(String... strings) { try { URL url1=new URL(strings[0]); HttpURLConnection connection = (HttpURLConnection) url1.openConnection(); int responseCode = connection.getResponseCode(); if(responseCode==200) { InputStream inputStream = connection.getInputStream(); int len=0; int progress=0; int current=0; int toatlLength = connection.getContentLength(); byte[] arr=new byte[1]; ByteArrayOutputStream bos=new ByteArrayOutputStream(); while((len=inputStream.read(arr))!=-1) { current+=len; progress = (int) ((float)current/toatlLength * 100); publishProgress(progress); bos.write(arr,0,len); } return BitmapFactory.decodeByteArray(bos.toByteArray(),0,bos.size()); } } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Bitmap bitmap) { iv.setImageBitmap(bitmap); lt.setVisibility(View.VISIBLE); } @Override protected void onProgressUpdate(Integer... values) { pg_bar.setProgress(values[0]); tv_progress.setText(values[0]+"%"); } } }
AsyncTask加载图片
最新推荐文章于 2021-05-28 17:45:33 发布