首页 > 代码库 > AsyncTask的使用 (二)图片下载,进度条
AsyncTask的使用 (二)图片下载,进度条
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; 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 android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.app.ProgressDialog; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { private ProgressDialog dialog; private Button button; private ImageView imageView; private String image_path = "http://i1.juyouqu.com/uploads/content//2014/04/1396611698344.jpg!w598"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); dialog = new ProgressDialog(this); dialog.setTitle("提示"); dialog.setMessage("正在下载......."); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // dialog.show(); button = (Button)findViewById(R.id.button1); imageView = (ImageView)findViewById(R.id.imageView1); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub new MyTask().execute(image_path); } }); } public class MyTask extends AsyncTask<String, Integer, Bitmap> { @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); dialog.show(); } @Override protected Bitmap doInBackground(String... params) { // TODO Auto-generated method stub Bitmap bitmap = null; ByteArrayOutputStream output = new ByteArrayOutputStream(); InputStream input = null; try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(params[0]); HttpResponse httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { input = httpResponse.getEntity().getContent(); long file_length = httpResponse.getEntity().getContentLength(); int len = 0; byte[] data = http://www.mamicode.com/new byte[1024];>
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。