我正在构建我的第一个android应用程序,并且遇到了问题。基本上,我试图将我用PHP构建的Youtube 2 Mp3页面移植到移动应用程序。我已成功完成此操作,但转换为mp3后遇到的问题是我无法从android应用程序页面上打印的链接下载mp3文件。它可以直接从网页上正常工作,如果我让应用程序在androids默认浏览器(Chrome)中加载链接,它也可以正常工作,但是当我让应用程序在WebView中加载链接时,它不起作用。

文件:MainActivity.java

    public class MainActivity extends AppCompatActivity {

WebView web;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    web = (WebView) findViewById(R.id.webView);

    web.setWebViewClient(new myWebClient());
    web.getSettings().setJavaScriptEnabled(true);

    web.loadUrl("http://www.bigjohn863.com/youtubetomp3/index.php");

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });
}

public class myWebClient extends WebViewClient
{
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        view.loadUrl(url);
        return false;

    }
}


网页:http://www.bigjohn863.com/youtubetomp3/index.php

该网页在常规浏览器中加载时可以按预期工作,并且如果我在android默认浏览器(Chrome)中使用它,也可以正常工作,但是如果我更改代码以仅在Webview中加载单击的链接,则当我单击链接时它什么也没做。

javascript - Android WebView不会从 anchor 标记加载远程URL-LMLPHP

最佳答案

验证shouldOverrideUrlLoading(WebView view, String url)后,尝试将其添加到函数url中。它将开始下载,类似于从任何网页下载

 if (url.endsWith(".mp3")) {
                Uri source = Uri.parse(url);
                // Make a new request pointing to the .mp3 url
                DownloadManager.Request request = new DownloadManager.Request(source);
                // appears the same in Notification bar while downloading
                request.setDescription("Description for the DownloadManager Bar");
                request.setTitle("YourMp3.mp3");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                    request.allowScanningByMediaScanner();
                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                }
                // save the file in the "Downloads" folder of SDCARD
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "MyMp3.mp3");
                // get download service and enqueue file
                DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                manager.enqueue(request);
            }

10-05 20:34
查看更多