ファイル (この場合は .mp4) へのリンクである webview のリンクをクリックすると、この小さなコードがここに表示されます。このコードは、デフォルトの Web ブラウザーに送信され、このファイル タイプを表示できるアプリを要求します。
myWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
私が欲しいのは、そのファイルリンクをクリックすると、天気にファイルをダウンロードまたは表示するように求めるダイアログが作成されることです。ダウンロードをクリックすると、 DownloadManager クラスを使用してそれを処理し、そのファイルをバックグラウンドでダウンロードして、完了時に警告します。そして、表示をクリックすると、Web ブラウザに行かずにこのファイルを表示できるアプリを求めるインテントを作成したいと考えています。
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, final String url) {
if (url.endsWith(".mp4")) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage(R.string.dialog_title)
.setCancelable(false)
.setPositiveButton(R.string.dialog_download, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Some descrition");
request.setTitle("Some title");
// in order for this if to run, you must use the android 3.2 to compile your app
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "name-of-the-file.ext");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
})
.setNegativeButton(R.string.dialog_play, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "video/mp4");
startActivity(intent);
}
});
}
});
AlertDialog alert = builder.create();
alert.show();
}
return false;
}
}
これで、ユーザーがクリックしたmp4ファイルをダウンロードまたは再生するようにユーザーに促すこのコードを取得しました。しかし、[再生] または [ダウンロード] をクリックすると、リンクを 2 回目にクリックするまで機能します。上記のコードのどこが間違っているのでしょうか。ありがとう。
私はAndroid開発とJavaに非常に慣れていません。誰かがこれを案内してくれれば、より速く学習するのに役立ちます. また、私の英語で申し訳ありません...