public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ProgressDialog pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//设置一个下载进度条
pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setProgress(0);
pd.setTitle("Downloadnow");
//设置响应事件
Button bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(this);
Button bt2 = (Button) findViewById(R.id.button2);
bt2.setOnClickListener(this);
Button bt3 = (Button) findViewById(R.id.button3);
bt3.setOnClickListener(this);
Button bt4 = (Button) findViewById(R.id.button4);
bt4.setOnClickListener(this);
Button bt5 = (Button) findViewById(R.id.button5);
bt5.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Img i = new Img();
System.out.println(v.getId());
switch (v.getId()) {
case R.id.button:
i.execute("http://image.i-voce.jp/files/article/main/s8AO3sFN_1438142266.jpg");
break;
case R.id.button2:
i.execute("http://pic.prepics-cdn.com/d75526b7cc13/41938040.jpeg");
break;
case R.id.button3:
i.execute("http://entertainment.rakuten.co.jp/movie/interview/kiritanimirei/img/interviewimg001.jpg");
break;
case R.id.button4:
i.execute("http://up.gc-img.net/post_img_web/2015/09/32f61210611d358bddc2784d875cf65e_4238.jpeg");
break;
case R.id.button5:
i.execute("http://lwoyr.com/wp-content/uploads/2015/06/20150618_5.jpg");
break;
}
}
public class Img extends AsyncTask<String, Integer, byte[]> {
@Override
protected byte[] doInBackground(String... params) {
byte[] reBate = null;
try {
URL url = new URL(params[0]);
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
huc.setConnectTimeout(3000);
huc.setReadTimeout(3000);
huc.setDoInput(true);
huc.setRequestMethod("GET");
//用文件长度设置进度条的最大值
pd.setMax(huc.getContentLength());
if (huc.getResponseCode() == 200) {
InputStream is = huc.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len = 0;
byte[] buf = new byte[1024];
while ((len = is.read(buf)) != -1) {
baos.write(buf, 0, len);
publishProgress(baos.size());
}
reBate = baos.toByteArray();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return reBate;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pd.show();
}
@Override
protected void onPostExecute(byte[] bytes) {
super.onPostExecute(bytes);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
ImageView iv = (ImageView) findViewById(R.id.imageView2);
iv.setImageBitmap(bitmap);
pd.dismiss();
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
pd.setProgress(values[0]);
}
}
}
0 件のコメント:
コメントを投稿