我正在构建我的第一个 Android 应用程序并遇到问题。基本上我正在尝试将 PHP 内置的 Youtube 2 Mp3 页面移植到移动应用程序。我已经成功完成了此操作,但我遇到的问题是转换为 mp3 后,我无法从 Android 应用程序页面上打印的链接下载 mp3 文件。它直接从网页工作正常,如果我让应用程序在 Android 默认浏览器(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 中加载单击的链接,那么当我单击链接时,它会正常工作什么都不做。
最佳答案
在验证 url
后,尝试将其添加到您的函数 shouldOverrideUrlLoading(WebView view, String 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);
}
关于javascript - Android WebView 不会从 anchor 标记加载远程 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34729498/