package com.peach.asynctask;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
private Button btn;
private ImageView img;
private String image_Path = "图片地址";
private ProgressDialog dialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
dialog = new ProgressDialog(this);
dialog.setTitle("提示信息");
dialog.setMessage("玩命下载中。。。");
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new MyTask().execute(image_Path);
}
});
}
private void initView() {
btn = (Button) findViewById(R.id.btn);
img = (ImageView) findViewById(R.id.img);
}
class MyTask extends AsyncTask<String,Void,Bitmap>{
@Override
protected void onPreExecute() {
dialog.show();
super.onPreExecute();
}
@Override
protected Bitmap doInBackground(String... params) {
HttpClient hc = new DefaultHttpClient();
HttpGet hg = new HttpGet(params[0]);
Bitmap bitmap = null;
HttpResponse hr = httpClient.execute(httpGet);
byte[] data = EntityUtils.toByteArray(HttpEntity);
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
return bitmap;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
xml
<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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btn"
android:src="@drawable/ic_launcher"/>
</RelativeLayout>