英文:
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 = "xyz.com/"; // 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("No internet connection available")
.setMessage("Please Check you're Mobile data or Wifi network.")
.setPositiveButton("Ok", 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<Uri[]> 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(".pdf")) {
// Handle PDF file download
return true;
}
// Handle other types of file downloads
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) {
// 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("http:") || url.startsWith("https:")) {
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() && 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("EXIT")
.setMessage("Are you sure. You want to close this app?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", 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,"no internet connection");
return false;
}
else
{
if(info.isConnected())
{
Log.d(TAG," internet connection available...");
return true;
}
else
{
Log.d(TAG," internet connection");
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("javascript:(function() { " +
"var videos = document.getElementsByTagName('video'); " +
"for(var i=0;i<videos.length;i++) { " +
"videos[i].setAttribute('webkit-playsinline', ''); " +
"videos[i].setAttribute('playsinline', ''); " +
"videos[i].setAttribute('controls', ''); " +
"videos[i].setAttribute('style', 'max-width:100%; height:auto;'); " +
"}" +
"var iframes = document.getElementsByTagName('iframe');" +
"for(var i=0;i<iframes.length;i++){" +
"if(iframes[i].src.includes('youtube') || iframes[i].src.includes('vimeo')) {" +
"iframes[i].setAttribute('frameborder', '0');" +
"iframes[i].setAttribute('allowfullscreen', '');" +
"iframes[i].setAttribute('webkitallowfullscreen', '');" +
"iframes[i].setAttribute('mozallowfullscreen', '');" +
"iframes[i].setAttribute('style', 'width:100%; height:100%;');" +
"}" +
"}" +
"})()");
}
}
}
`
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">
<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>`
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论