当在Android设备上单击按钮时如何从网址下载图片

时间:2018-08-23 07:05:00

标签: android

单击按钮时,我试图在URL中下载图像文件。我已经编写了此代码,当点击了图片网址时,该代码会自动下载,但是我想添加一个按钮,然后单击按钮时,下载应该开始。

我的Java代码。

public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.endsWith(".jpg")){
DownloadManager.Request request = new DownloadManager.Request(
                         Uri.parse(url));
request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
                 request.setDestinationInExternalPublicDir("/Happy", "Happy.jpg");
                 DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                 dm.enqueue(request);
                 Toast.makeText(getApplicationContext(), "Downloading File", 
                         Toast.LENGTH_LONG).show(); 
            }
          view.loadUrl(url);
            return true;
        }

2 个答案:

答案 0 :(得分:1)

您可以在XML代码中添加按钮,并将函数应用于onClick参数。您可以通过“属性” GUI来执行此操作,或者直接在XML代码中键入它。

GUI界面(单击即可执行playSpeech()方法):

enter image description here

XML代码(将调用callTheFunction()):

<Button
    android:id="@+id/button"
    android:onClick="callTheFunction" />

或者您可以通过以下方式使用Java代码:

((Button) findViewById(R.id.button)).setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        callTheFunction();
    }
});

请注意,此示例中的callTheFunction()playSpeech()方法需要创建

答案 1 :(得分:1)

由于您处于Web视图中,因此可以将URL保存在字段中的某个位置,然后当用户点击按钮时,发送下载请求。

  public String downloadUrl;


  public boolean shouldOverrideUrlLoading(WebView view, String url) {
       if (url.endsWith(".jpg")){
            downloadUrl = url;
       }
       view.loadUrl(url);
       return true;
 }

当用户点击按钮时,您可以发起下载请求

btnDownload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    // Download here using downloadUrl
    DownloadManager.Request request = new DownloadManager.Request(
                     Uri.parse(downloadUrl));
    request.allowScanningByMediaScanner(); 
    request.setNotificationVisibility(DownloadManager.
    Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); 
             request.setDestinationInExternalPublicDir("/Happy", "Happy.jpg");
             DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
             dm.enqueue(request);
             Toast.makeText(getApplicationContext(), "Downloading File", 
                     Toast.LENGTH_LONG).show();

   }
  });