publicclass MainActivity extends Activity {
privatefinalstatic String TAG = "MainActivity";
private String urlString = "http://www.baidu.com/";
private TextView text_main_info;
@Override
protectedvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_main_info = (TextView) findViewById(R.id.text_main_info);
// 调用异步任务,执行网络访问
new MyTask(this).execute(urlString);
}
class MyTask extends AsyncTaskbyte[]> {
private ProgressDialog pDialog;
private Context context = null;
// 构造方法,初始化进度对话框
public MyTask(Context context) {
this.context = context;
pDialog = new ProgressDialog(context);
pDialog.setIcon(R.drawable.ic_launcher);
pDialog.setTitle("提示:");
pDialog.setMessage("数据加载中。。。");
}
// 事先执行方法中显示进度对话框
@Override
protectedvoid onPreExecute() {
pDialog.show();
super.onPreExecute();
}
// 进度条进度改变方法。一般情况下,可以不写该方法
@Override
protectedvoid onProgressUpdate(Void... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
// 后台执行方法,这个方法执行worker Thread异步访问网络,加载数据。该方法中不可以执行任何UI操作。
@Override
protectedbyte[] doInBackground(String... params) {
BufferedInputStream bis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
URL urlObj = new URL(params[0]);
HttpURLConnection httpConn = (HttpURLConnection) urlObj
.openConnection();
httpConn.setDoInput(true);
// httpConn.setDoOutput(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == 200) {
bis = new BufferedInputStream(httpConn.getInputStream());
byte[] buffer = newbyte[1024 * 8];
int c = 0;
while ((c = bis.read(buffer)) != -1) {
baos.write(buffer, 0, c);
baos.flush();
}
// Toast.makeText(context, baos.toByteArray().toString(),
// Toast.LENGTH_LONG).show();
return baos.toByteArray();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
if (baos != null) {
baos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
returnnull;
}
// 事后方法,这个方法主要作用是执行对主线程中UI的操作。可以实现主线程和子线程之间的数据交互
@Override
protectedvoid onPostExecute(byte[] result) {
super.onPostExecute(result);
if (result == null) {
text_main_info.setText("网络异常,加载数据失败!");
} else {
text_main_info.setText(new String(result));
}
pDialog.dismiss();
}
}
@Override
publicboolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
returntrue;
}
}