web view文件下载和上传文件问题

huangapple go评论64阅读模式
英文:

web view file download and upload file issue

问题

我使用Android Studio将我的网站转换成WebView APK,但上传和下载功能不起作用。我已经添加了所有必要的权限,但仍然面临以下问题,以下是我的MainActivity.java代码:

package com.example.eprepareacademy2o;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.DownloadListener;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    String websiteURL = "xyz.com/"; // 设置网站URL

    private WebView webview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (!CheckNetwork.isInternetAvailable(this)) // 如果没有网络连接
        {
            setContentView(R.layout.activity_main);

            new AlertDialog.Builder(this)
                    .setTitle("没有可用的互联网连接")
                    .setMessage("请检查您的移动数据或Wi-Fi网络。")
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .show();

        } else {
            // WebView设置
            webview = findViewById(R.id.webView);
            webview.getSettings().setJavaScriptEnabled(true);
            webview.getSettings().setAllowFileAccess(true);
            webview.getSettings().setAllowFileAccessFromFileURLs(true);
            webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
            webview.setWebChromeClient(new WebChromeClient() {
                public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                    // 处理文件上传
                    return true;
                }
            });

            webview.setDownloadListener(new DownloadListener() {
                public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                    // 处理文件下载
                }
            });

            webview.setWebViewClient(new WebViewClient() {
                public boolean shouldOverrideUrlLoading(WebView webView, String url) {
                    if (url.endsWith(".pdf")) {
                        // 处理PDF文件下载
                        return true;
                    }
                    // 处理其他类型的文件下载
                    return false;
                }
            });

            webview.loadUrl("xyz.com/");

            webview.getSettings().setDomStorageEnabled(true);
            webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
            webview.loadUrl(websiteURL);
            webview.setWebViewClient(new WebViewClientDemo());
            webview.setWebChromeClient(new WebChromeClient() {
                @Override
                public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
                    // 处理文件上传
                    return true;
                }
            });
        }
    }

    private class WebViewClientDemo extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("http:") || url.startsWith("https:")) {
                view.loadUrl(url);
                return true;
            } else {
                view.loadUrl(websiteURL + url);
                return true;
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (webview.isFocused() && webview.canGoBack()) {
            webview.goBack();
        } else {
            new AlertDialog.Builder(this)
                    .setTitle("退出")
                    .setMessage("确定要关闭此应用吗?")
                    .setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .setNegativeButton("否", null)
                    .show();
        }
    }
}

class CheckNetwork {
    private static final String TAG = CheckNetwork.class.getSimpleName();

    public static boolean isInternetAvailable(Context context) {
        NetworkInfo info = (NetworkInfo) ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

        if (info == null) {
            Log.d(TAG, "没有互联网连接");
            return false;
        } else {
            if (info.isConnected()) {
                Log.d(TAG, "有互联网连接...");
                return true;
            } else {
                Log.d(TAG, "互联网连接");
                return true;
            }
        }
    }
}

另外,这是包含必要权限的AndroidManifest.xml文件:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:usesCleartextTraffic="true"
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@drawable/ic_launcher_foreground"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.EprepareAcademy2O"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="false" />
        <activity
            android:name=".SplashActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

这是您的MainActivity.java和AndroidManifest.xml文件的中文翻译,希望能有所帮助。请继续检查您的WebView设置和权限,确保一切配置正确,以使文件上传和下载功能正常工作。如果问题仍然存在,请提供更多详细信息,以便进一步帮助解决。

英文:

i convert my website to webview apk using android studio but the upload and download functionality not working, i added all necessary permission but still facing this issue below is my Mainactivity.java code

`
package com.example.eprepareacademy2o;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.DownloadListener;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
String websiteURL = &quot;xyz.com/&quot;; // sets web url
private WebView webview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if( ! CheckNetwork.isInternetAvailable(this)) //returns true if internet available
{
//if there is no internet do this
setContentView(R.layout.activity_main);
new AlertDialog.Builder(this) //alert the person knowing they are about to close
.setTitle(&quot;No internet connection available&quot;)
.setMessage(&quot;Please Check you&#39;re Mobile data or Wifi network.&quot;)
.setPositiveButton(&quot;Ok&quot;, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.show();
}
else
{
//Webview stuff
webview = findViewById(R.id.webView);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setAllowFileAccess(true);
webview.getSettings().setAllowFileAccess(true);
webview.getSettings().setAllowFileAccessFromFileURLs(true);
webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
webview.setWebChromeClient(new WebChromeClient() {
public boolean onShowFileChooser(WebView webView, ValueCallback&lt;Uri[]&gt; filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
// Handle file upload
return true;
}
});
webview.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
// Handle file download
}
});
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if (url.endsWith(&quot;.pdf&quot;)) {
// Handle PDF file download
return true;
}
// Handle other types of file downloads
return false;
}
});
webview.loadUrl(&quot;xyz.com/&quot;);
webview.getSettings().setDomStorageEnabled(true);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webview.loadUrl(websiteURL);
webview.setWebViewClient(new WebViewClientDemo());
webview.setWebChromeClient(new WebChromeClient() {
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback&lt;Uri[]&gt; filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
// Handle file upload
return true;
}
});
}
}
private class WebViewClientDemo extends WebViewClient {
@Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith(&quot;http:&quot;) || url.startsWith(&quot;https:&quot;)) {
view.loadUrl(url);
return true;
} else {
//Handle internal links
view.loadUrl(websiteURL + url);
return true;
}
}
}
@Override
public void onBackPressed() { //if user presses the back button do this
if (webview.isFocused() &amp;&amp; webview.canGoBack()) { //check if in webview and the user can go back
webview.goBack(); //go back in webview
} else { //do this if the webview cannot go back any further
new AlertDialog.Builder(this) //alert the person knowing they are about to close
.setTitle(&quot;EXIT&quot;)
.setMessage(&quot;Are you sure. You want to close this app?&quot;)
.setPositiveButton(&quot;Yes&quot;, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton(&quot;No&quot;, null)
.show();
}
}
}
class CheckNetwork {
private static final String TAG = CheckNetwork.class.getSimpleName();
public static boolean isInternetAvailable(Context context)
{
NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null)
{
Log.d(TAG,&quot;no internet connection&quot;);
return false;
}
else
{
if(info.isConnected())
{
Log.d(TAG,&quot; internet connection available...&quot;);
return true;
}
else
{
Log.d(TAG,&quot; internet connection&quot;);
return true;
}
}
}
private class WebViewClientDemo extends WebViewClient {
@Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
// Enable full screen for embedded items
view.loadUrl(&quot;javascript:(function() { &quot; +
&quot;var videos = document.getElementsByTagName(&#39;video&#39;); &quot; +
&quot;for(var i=0;i&lt;videos.length;i++) { &quot; +
&quot;videos[i].setAttribute(&#39;webkit-playsinline&#39;, &#39;&#39;); &quot; +
&quot;videos[i].setAttribute(&#39;playsinline&#39;, &#39;&#39;); &quot; +
&quot;videos[i].setAttribute(&#39;controls&#39;, &#39;&#39;); &quot; +
&quot;videos[i].setAttribute(&#39;style&#39;, &#39;max-width:100%; height:auto;&#39;); &quot; +
&quot;}&quot; +
&quot;var iframes = document.getElementsByTagName(&#39;iframe&#39;);&quot; +
&quot;for(var i=0;i&lt;iframes.length;i++){&quot; +
&quot;if(iframes[i].src.includes(&#39;youtube&#39;) || iframes[i].src.includes(&#39;vimeo&#39;)) {&quot; +
&quot;iframes[i].setAttribute(&#39;frameborder&#39;, &#39;0&#39;);&quot; +
&quot;iframes[i].setAttribute(&#39;allowfullscreen&#39;, &#39;&#39;);&quot; +
&quot;iframes[i].setAttribute(&#39;webkitallowfullscreen&#39;, &#39;&#39;);&quot; +
&quot;iframes[i].setAttribute(&#39;mozallowfullscreen&#39;, &#39;&#39;);&quot; +
&quot;iframes[i].setAttribute(&#39;style&#39;, &#39;width:100%; height:100%;&#39;);&quot; +
&quot;}&quot; +
&quot;}&quot; +
&quot;})()&quot;);
}
}
}
`

also here is Androidminifist folder which contain necessary permission
`<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;
&lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt;
&lt;uses-permission android:name=&quot;android.permission.CAMERA&quot; /&gt;
&lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;
&lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;
&lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot;/&gt;
&lt;application
android:usesCleartextTraffic=&quot;true&quot;
android:allowBackup=&quot;true&quot;
android:dataExtractionRules=&quot;@xml/data_extraction_rules&quot;
android:fullBackupContent=&quot;@xml/backup_rules&quot;
android:icon=&quot;@drawable/ic_launcher_foreground&quot;
android:label=&quot;@string/app_name&quot;
android:supportsRtl=&quot;true&quot;
android:theme=&quot;@style/Theme.EprepareAcademy2O&quot;
tools:targetApi=&quot;31&quot;&gt;
&lt;activity
android:name=&quot;.MainActivity&quot;
android:exported=&quot;false&quot; /&gt;
&lt;activity
android:name=&quot;.SplashActivity&quot;
android:exported=&quot;true&quot;&gt;
&lt;intent-filter&gt;
&lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
&lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
&lt;/intent-filter&gt;
&lt;/activity&gt;
&lt;/application&gt;

</manifest>`

i convert my website to a webview apk using android studio, it working properly but the upload and download files button not working.
tried more than 50+ videos on youtube and many articles but still issue with these

答案1

得分: 0

如果您正在使用Android 13,请确保添加READ_MEDIA_IMAGES权限。

英文:

If you are using android 13, make sure you add READ_MEDIA_IMAGES permissions.

答案2

得分: 0

使用Android 13时,我遇到了相同的问题,它无法打开存储,所以我在清单文件中添加了权限:

<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
<uses-permission android:name="android.permission.READ_MEDIA_AUDIO" />
英文:

Using android 13 I had the same issue, it wouldn't open storage, so I added permissions in manifest :

uses-permission android:name= android.permission.READ_MEDIA_IMAGES
uses-permission android:name= android.permission.READ_MEDIA_VIDEO
uses-permission android:name= android.permission.READ_MEDIA_AUDIO

huangapple
  • 本文由 发表于 2023年3月15日 20:33:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75744746.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定