0

我一直在学习 Android Studio(我不是专家)。但是,我设法从一个网站编写了我的 WebView 应用程序,但我无法让它将文件作为原始文件名下载......由于某种原因,我得到了一个“admin-ajax.php”文件作为回报。

这是 MainActivity.java 上的代码:

  mywebView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long l) {
            //file name
            String fileName = URLUtil.guessFileName(url,contentDisposition,getFileType(url));
            sFileName = fileName.substring(fileName.lastIndexOf('/')+1);
            sURL = url;
            sUserAgent = userAgent;

            //check android version
            if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
                if (ContextCompat.checkSelfPermission( MainActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE)
    ==PackageManager.PERMISSION_GRANTED){
                    downloadFile(fileName,url,userAgent);
                }else {
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}
                    ,  1001);
                    }
                }else{
                    downloadFile(fileName,url,userAgent);

                }
            
            }

        public void onPageStarted(WebView view,String url, Bitmap favicon){
            onPageStarted (view,url, favicon);
        }

        });

    }

@Override
public void onBackPressed() {
    if (webView.canGoBack())
        webView.goBack();
    else
    super.onBackPressed();
}

public String getFileType(String url){
    ContentResolver contentResolver = getContentResolver();
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    return mimeTypeMap.getExtensionFromMimeType(contentResolver.getType(Uri.parse(url)));
}

    private void downloadFile(String fileName, String url, String userAgent){
        try {
            DownloadManager downloadManager = (DownloadManager)getSystemService(DOWNLOAD_SERVICE);
            DownloadManager.Request request = new DownloadManager.Request (Uri.parse(url));
            String cookie  = CookieManager.getInstance().getCookie(url);
            request.setTitle(fileName)
                    .setDescription("is being downloaded")
                    .addRequestHeader("cookie",cookie)
                    .addRequestHeader("User - Agent", userAgent)
                    .setMimeType(getFileType(url))
                    .setAllowedOverMetered(true)
                    .setAllowedOverRoaming(true)
                    .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE
                    |DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                    downloadManager.enqueue(request);
            sURL = "";
            sUserAgent = "";
            sFileName = "";
            Toast.makeText( this, "Download Started", Toast.LENGTH_SHORT).show();

        }catch (Exception ignored){
            Toast.makeText( this, "error"+ignored, Toast.LENGTH_SHORT).show();

        }
    }


public void onRequestPermissionResult(int requestCode, @NonNull String [] permissions, int[] grantResults){
    super.onRequestPermissionsResult(requestCode,permissions,grantResults);
    if (requestCode==1001){
        if (grantResults.length>0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
            if (!sURL.equals("")&&!sFileName.equals("")&&!sUserAgent.equals("")){
                downloadFile(sFileName,sURL,sUserAgent);
            }
        }
    }
}

可能是什么问题?

谢谢大家的支持。

亲切的问候,

4

1 回答 1

0

使用下面的代码。如果出现以下情况,请替换i.setDataAndType(uri, "application/pdf");为另一种类型的文件扩展名:

  1. 文件扩展名不是 pdf;和

  2. 您想在下载后打开文件。

    public class WebViewActivity extends AppCompatActivity {
    
    ...
    
     private String fileName;
    
     @Override
     protected void onCreate(@Nullable Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
    
         ...
    
         webView.setDownloadListener(new DownloadListener() {
         @Override
         public void onDownloadStart(String url, String userAgent, String contentDisposition,
                                     String mimeType, long contentLength) {
             DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
             //setup the fileName
             //fileName = URLUtil.guessFileName(url,contentDisposition,mimeType);
             fileName = (contentDisposition.substring(contentDisposition.lastIndexOf("filename*=UTF-8")+17));
    
             request.setMimeType(mimeType);
             String cookies = CookieManager.getInstance().getCookie(url);
             request.addRequestHeader("cookie",cookies);
             request.addRequestHeader("User-Agent",userAgent);
             request.setDescription("Downloading File");
             request.setTitle(fileName));
             request.allowScanningByMediaScanner();
             request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
             request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,
                     fileName);
             DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
             //Registering receiver in Download Manager
             registerReceiver(onCompleted, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));    
             downloadManager.enqueue(request);
             Toast.makeText(getApplicationContext(), "Downloading File", Toast.LENGTH_SHORT).show();
         }
    
     });
    
     ...
    
     BroadcastReceiver onCompleted = new BroadcastReceiver() {
         @Override
         public void onReceive(Context context, Intent intent) {
             Toast.makeText(context.getApplicationContext(), "Download Finish", Toast.LENGTH_SHORT).show();
             File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/" + fileName);
             Uri uri = FileProvider.getUriForFile(WebViewActivity.this, "com.example.app"+".provider",file);
             Intent i = new Intent(Intent.ACTION_VIEW);
             i.setDataAndType(uri, "application/pdf");
             i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_GRANT_READ_URI_PERMISSION);
             startActivity(i);
         }
     };
    }
    
于 2021-09-26T19:58:40.340 回答