AsyncTask异步访问网络,ui线程做耗时操作,会造成线程阻塞。因此只能把获取网络放在子线程操作
写个方法继承AsyncTask
使用异步任务的规则:1.声明一个类继承AsyncTask,标注3个参数类型。
2.第一个参数表示执行的获取网络的路径
第二个参数表示进度的刻度
第三个参数表示返回的结果
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button = (android.widget.Button) findViewById(R.id.btn); ImageView = (android.widget.ImageView) findViewById(R.id.image); dialog = new ProgressDialog(this); dialog.setTitle("提示信息"); dialog.setMessage("正在下载,请稍后...."); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setCancelable(false); Button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Myantask().execute();//调用获取网络的方法 } }); }
/** * 执行下载前的任务类 */ public class Myantask extends AsyncTask<String, Void, Bitmap> { @Override protected void onPreExecute() { super.onPreExecute(); dialog.show(); }
/** * 网络获取的操作 */ @Override protected Bitmap doInBackground(String... params) { Bitmap bitmap = null; InputStream is = null; try { URL url = new URL("http://img1.gtimg.com/news/pics/hv1/37/195/1468/95506462.jpg"); HttpURLConnection Connection = (HttpURLConnection) url.openConnection(); Connection.setDoOutput(true); Connection.setDoInput(true); Connection.setConnectTimeout(10000); Connection.setRequestMethod("GET"); Connection.connect(); if (Connection.getResponseCode() == 200) { is = Connection.getInputStream(); bitmap = BitmapFactory.decodeStream(is); is.close(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return bitmap;
}
/* * 跟新UI的操作 * */ @Override protected void onPostExecute(Bitmap bitmap) { super.onPostExecute(bitmap); ImageView.setImageBitmap(bitmap); }布局代码:<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.asus_pc.hander.MainActivity"> <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_alignParentTop="true" android:src="@mipmap/ic_launcher" /> <Button android:id="@+id/btn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="30sp" android:layout_centerHorizontal="true" android:layout_alignParentBottom="true" android:text="下载网络图片" /> </RelativeLayout>