关于AsyncTask异步执行任务Demo-创新互联
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); } }
//任务类
目前创新互联建站已为1000+的企业提供了网站建设、域名、网页空间、网站托管维护、企业网站设计、邵武网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。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{ public String imgPath; private byte[] data; public ImageView img; protected void onPrepareExecute(){ Log.v("task", "onPrepareExecute"); super.onPreExecute(); } // doInBackground方法内部执行后台任务,不可在此方法内修改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方法用于在执行完后台任务后更新UI,显示结果 @Override protected void onPostExecute(String result) { // progressDialog.dismiss(); Log.v("task", "onPostExecute"); Bitmap bmp=BitmapFactory.decodeByteArray(data, 0, data.length); img.setImageBitmap(bmp); } // onCancelled方法用于在取消执行中的任务时更改UI @Override protected void onCancelled() { Log.v("task", "onCancelled"); } }
//。xml中只有一个ImageView控件
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
网页标题:关于AsyncTask异步执行任务Demo-创新互联
本文网址:http://pwwzsj.com/article/csdppj.html