我正在尝试使用对话框中的“打开”按钮来打开特定文件。
这就是我尝试过的Open a file downloaded using download manager Android
package com.conquest.conquestcapital;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.webkit.DownloadListener;
import android.webkit.URLUtil;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity
{
WebView mWebView;
SwipeRefreshLayout swipe;
private Activity mActivity;
private Context mContext;
private static final int MY_PERMISSION_REQUEST_CODE = 123;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
swipe = (SwipeRefreshLayout) findViewById(R.id.swipe);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener()
{
public void onRefresh(){
LoadWeb();
}
});
LoadWeb();
}
public void LoadWeb() {
mContext = getApplicationContext();
mActivity = MainActivity.this;
mWebView = (WebView) findViewById(R.id.webView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setAppCacheEnabled(true);
mWebView.setVerticalScrollBarEnabled(true);
mWebView.setHorizontalScrollBarEnabled(true);
final String url = "https://www.conquestcapitalltd.com/";
mWebView.loadUrl(url);
swipe.setRefreshing(true);
checkPermission();
mWebView.setWebViewClient(new WebViewClient() {
//public void onReveivedError(WebView view, int errorCode, String description, String failingUrl){
// mWebView.loadUrl("file://android_asset/error.html");
//}
public void onPageFinished(WebView view, String url) {
//hide the swipe refreshlayout
swipe.setRefreshing(false);
}
});
mWebView.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDescription,
String mimetype, long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
final String fileName = URLUtil.guessFileName(url, contentDescription, mimetype);
if (fileName != null && !TextUtils.isEmpty(fileName)) {
File file = new File(Environment.getExternalStorageDirectory().toString() + File.separator + Environment.DIRECTORY_DOWNLOADS, "/" + fileName);
if (file.exists()) {
AlertDialog.Builder warningMessage = new AlertDialog.Builder(MainActivity.this);
warningMessage.setMessage("The file already exists. Click open")
.setCancelable(false)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton("open", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
File file = new File(Environment.getExternalStorageDirectory().toString() + File.separator + Environment.DIRECTORY_DOWNLOADS, "/" + fileName);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "capital-company-profile-2016/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "File not found", Toast.LENGTH_SHORT).show();
}
}
});
warningMessage.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
warningMessage.show();
} else {
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager dManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dManager.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File...", Toast.LENGTH_LONG).show();
Uri uri = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
}
}
});
}
protected void checkPermission () {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//Alert Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
builder.setMessage("Write external storage permission is required.");
builder.setTitle("Please grant permission");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSION_REQUEST_CODE
);
}
});
builder.setNeutralButton("Cancel", null);
AlertDialog dialog = builder.create();
dialog.show();
} else {
ActivityCompat.requestPermissions(
mActivity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSION_REQUEST_CODE
);
}
} else {
//permission already granted
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode){
case MY_PERMISSION_REQUEST_CODE:{
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
}else{
//permission denied
}
}
}
}
@Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
我希望当用户从Web视图中按下载时,出现一个对话框,再按一次下载时,会出现一个警告按钮,并且当单击“打开”时,用户可以在应用程序中打开文件。