您好,登錄后才能下訂單哦!
public class MainActivity extends Activity { private String url = "https://cache.yisu.com/upload/information/20200311/46/200000.jpg"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); testTask(); } public void testTask(){ DownloadPicTask task = new DownloadPicTask(); task.imgPath = url; task.img = (ImageView) findViewById(R.id.p_w_picpathView1); task.execute(url); } }
//任務(wù)類
package com.example.task; 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.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.Log; import android.widget.ImageView; public class DownloadPicTask extends AsyncTask<String, Integer, String>{ public String imgPath; private byte[] data; public ImageView img; protected void onPrepareExecute(){ Log.v("task", "onPrepareExecute"); super.onPreExecute(); } // doInBackground方法內(nèi)部執(zhí)行后臺任務(wù),不可在此方法內(nèi)修改UI @Override protected String doInBackground(String... arg0) { // TODO Auto-generated method stub Log.v("task", "doInBackground " + arg0); HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(imgPath); HttpResponse httpResponse = null; try { httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { data = EntityUtils.toByteArray(httpResponse .getEntity()); } } catch (Exception e) { e.printStackTrace(); } return null; } // onProgressUpdate方法用于更新進度信息 @Override protected void onProgressUpdate(Integer... progresses) { Log.v("task", "onProgressUpdate"); super.onProgressUpdate(progresses); } // onPostExecute方法用于在執(zhí)行完后臺任務(wù)后更新UI,顯示結(jié)果 @Override protected void onPostExecute(String result) { // progressDialog.dismiss(); Log.v("task", "onPostExecute"); Bitmap bmp=BitmapFactory.decodeByteArray(data, 0, data.length); img.setImageBitmap(bmp); } // onCancelled方法用于在取消執(zhí)行中的任務(wù)時更改UI @Override protected void onCancelled() { Log.v("task", "onCancelled"); } }
//。xml中只有一個ImageView控件
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。