自动从服务器下载图像

问题描述:

如何在不按按钮的情况下从服务器下载图像。代码运行正常,但只有按下按钮才能下载。如何自动进行下载图像自动从服务器下载图像

@覆盖 公共无效的onClick(查看视图){ 开关(view.getId()){ 情况R.id.bDownloadImage: 新DonwloadImage(downloadImageName.getText() 。的ToString())执行(); 休息; }}

private class DonwloadImage extends AsyncTask<Void, Void, Bitmap> { 
    String name; 
    ProgressDialog loading; 
    public DonwloadImage (String name){//constractor 
     this.name = name; 
    } 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     mProgressDialog = new ProgressDialog(Receiver.this); 
     mProgressDialog.setTitle("Downloading Image"); // title of progress dialog 
     mProgressDialog.setMessage("Loading..."); // message displaying 
     mProgressDialog.setIndeterminate(false); 
     mProgressDialog.show(); // show method 
    } 


    @Override 
    protected Bitmap doInBackground(Void... voids) { 
     // loading.dismiss(); 
     String url = SERVER_ADDRESS + "pictures/" + name + ".JPG"; 
     try 
     { 
      URLConnection connection = new URL(url).openConnection(); 
      connection.setConnectTimeout(1000 * 30); 
      connection.setReadTimeout(1000 * 30); 

      return BitmapFactory.decodeStream((InputStream) connection.getContent(), null, null); 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
      return null; 
     } 
    } 


    @Override 
    protected void onPostExecute(Bitmap bitmap) 
    { 
     super.onPostExecute(bitmap); 
     if(bitmap != null) 
     { 
      downloadImage.setImageBitmap(bitmap); 
      mProgressDialog.dismiss(); 
     } 
    } 
} 
+0

步骤#1:选择您需要下载的触发事件。第二步:发生该事件时执行你的'AsyncTask'。 – CommonsWare

你应该在的onCreate添加

DonwloadImage(downloadImageName.getText().toString()).execute(); 

活动,为autoDownload财产。

+1

是的,但也有补充。 new DonwloadImage(downloadImageName.getText()。toString())。execute(); 。谢谢你bthw。 – Meli