如何在不按Android Studio按钮的情况下从服务器下载图像。代码运行正常,但只有按下按钮才能下载。如何自动下载图像
@覆盖 public void onClick(查看视图){ switch(view.getId()){ case R.id.bDownloadImage: new DonwloadImage(downloadImageName.getText()。toString())。execute(); 打破; } }
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 :(得分:0)
你应该添加
DonwloadImage(downloadImageName.getText().toString()).execute();
在onCreate of Activity中,用于autoDownload属性。