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

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

web view file download and upload file issue

问题

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

  1. package com.example.eprepareacademy2o;
  2. import android.app.AlertDialog;
  3. import android.content.Context;
  4. import android.content.DialogInterface;
  5. import android.net.ConnectivityManager;
  6. import android.net.NetworkInfo;
  7. import android.net.Uri;
  8. import android.os.Bundle;
  9. import android.util.Log;
  10. import android.view.Window;
  11. import android.webkit.DownloadListener;
  12. import android.webkit.ValueCallback;
  13. import android.webkit.WebChromeClient;
  14. import android.webkit.WebView;
  15. import android.webkit.WebViewClient;
  16. import androidx.appcompat.app.AppCompatActivity;
  17. public class MainActivity extends AppCompatActivity {
  18. String websiteURL = "xyz.com/"; // 设置网站URL
  19. private WebView webview;
  20. @Override
  21. protected void onCreate(Bundle savedInstanceState) {
  22. super.onCreate(savedInstanceState);
  23. setContentView(R.layout.activity_main);
  24. if (!CheckNetwork.isInternetAvailable(this)) // 如果没有网络连接
  25. {
  26. setContentView(R.layout.activity_main);
  27. new AlertDialog.Builder(this)
  28. .setTitle("没有可用的互联网连接")
  29. .setMessage("请检查您的移动数据或Wi-Fi网络。")
  30. .setPositiveButton("确定", new DialogInterface.OnClickListener() {
  31. @Override
  32. public void onClick(DialogInterface dialog, int which) {
  33. finish();
  34. }
  35. })
  36. .show();
  37. } else {
  38. // WebView设置
  39. webview = findViewById(R.id.webView);
  40. webview.getSettings().setJavaScriptEnabled(true);
  41. webview.getSettings().setAllowFileAccess(true);
  42. webview.getSettings().setAllowFileAccessFromFileURLs(true);
  43. webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
  44. webview.setWebChromeClient(new WebChromeClient() {
  45. public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
  46. // 处理文件上传
  47. return true;
  48. }
  49. });
  50. webview.setDownloadListener(new DownloadListener() {
  51. public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
  52. // 处理文件下载
  53. }
  54. });
  55. webview.setWebViewClient(new WebViewClient() {
  56. public boolean shouldOverrideUrlLoading(WebView webView, String url) {
  57. if (url.endsWith(".pdf")) {
  58. // 处理PDF文件下载
  59. return true;
  60. }
  61. // 处理其他类型的文件下载
  62. return false;
  63. }
  64. });
  65. webview.loadUrl("xyz.com/");
  66. webview.getSettings().setDomStorageEnabled(true);
  67. webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
  68. webview.loadUrl(websiteURL);
  69. webview.setWebViewClient(new WebViewClientDemo());
  70. webview.setWebChromeClient(new WebChromeClient() {
  71. @Override
  72. public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
  73. // 处理文件上传
  74. return true;
  75. }
  76. });
  77. }
  78. }
  79. private class WebViewClientDemo extends WebViewClient {
  80. @Override
  81. public boolean shouldOverrideUrlLoading(WebView view, String url) {
  82. if (url.startsWith("http:") || url.startsWith("https:")) {
  83. view.loadUrl(url);
  84. return true;
  85. } else {
  86. view.loadUrl(websiteURL + url);
  87. return true;
  88. }
  89. }
  90. }
  91. @Override
  92. public void onBackPressed() {
  93. if (webview.isFocused() && webview.canGoBack()) {
  94. webview.goBack();
  95. } else {
  96. new AlertDialog.Builder(this)
  97. .setTitle("退出")
  98. .setMessage("确定要关闭此应用吗?")
  99. .setPositiveButton("是", new DialogInterface.OnClickListener() {
  100. @Override
  101. public void onClick(DialogInterface dialog, int which) {
  102. finish();
  103. }
  104. })
  105. .setNegativeButton("否", null)
  106. .show();
  107. }
  108. }
  109. }
  110. class CheckNetwork {
  111. private static final String TAG = CheckNetwork.class.getSimpleName();
  112. public static boolean isInternetAvailable(Context context) {
  113. NetworkInfo info = (NetworkInfo) ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
  114. if (info == null) {
  115. Log.d(TAG, "没有互联网连接");
  116. return false;
  117. } else {
  118. if (info.isConnected()) {
  119. Log.d(TAG, "有互联网连接...");
  120. return true;
  121. } else {
  122. Log.d(TAG, "互联网连接");
  123. return true;
  124. }
  125. }
  126. }
  127. }

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

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools">
  4. <uses-permission android:name="android.permission.INTERNET" />
  5. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  6. <uses-permission android:name="android.permission.CAMERA" />
  7. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  8. <uses-permission android:name="android.permission.INTERNET" />
  9. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
  10. <application
  11. android:usesCleartextTraffic="true"
  12. android:allowBackup="true"
  13. android:dataExtractionRules="@xml/data_extraction_rules"
  14. android:fullBackupContent="@xml/backup_rules"
  15. android:icon="@drawable/ic_launcher_foreground"
  16. android:label="@string/app_name"
  17. android:supportsRtl="true"
  18. android:theme="@style/Theme.EprepareAcademy2O"
  19. tools:targetApi="31">
  20. <activity
  21. android:name=".MainActivity"
  22. android:exported="false" />
  23. <activity
  24. android:name=".SplashActivity"
  25. android:exported="true">
  26. <intent-filter>
  27. <action android:name="android.intent.action.MAIN" />
  28. <category android:name="android.intent.category.LAUNCHER" />
  29. </intent-filter>
  30. </activity>
  31. </application>
  32. </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

  1. `
  2. package com.example.eprepareacademy2o;
  3. import android.app.AlertDialog;
  4. import android.content.Context;
  5. import android.content.DialogInterface;
  6. import android.net.ConnectivityManager;
  7. import android.net.NetworkInfo;
  8. import android.net.Uri;
  9. import android.os.Bundle;
  10. import android.util.Log;
  11. import android.view.Window;
  12. import android.webkit.DownloadListener;
  13. import android.webkit.ValueCallback;
  14. import android.webkit.WebChromeClient;
  15. import android.webkit.WebView;
  16. import android.webkit.WebViewClient;
  17. import androidx.appcompat.app.AppCompatActivity;
  18. public class MainActivity extends AppCompatActivity {
  19. String websiteURL = &quot;xyz.com/&quot;; // sets web url
  20. private WebView webview;
  21. @Override
  22. protected void onCreate(Bundle savedInstanceState) {
  23. super.onCreate(savedInstanceState);
  24. setContentView(R.layout.activity_main);
  25. if( ! CheckNetwork.isInternetAvailable(this)) //returns true if internet available
  26. {
  27. //if there is no internet do this
  28. setContentView(R.layout.activity_main);
  29. new AlertDialog.Builder(this) //alert the person knowing they are about to close
  30. .setTitle(&quot;No internet connection available&quot;)
  31. .setMessage(&quot;Please Check you&#39;re Mobile data or Wifi network.&quot;)
  32. .setPositiveButton(&quot;Ok&quot;, new DialogInterface.OnClickListener() {
  33. @Override
  34. public void onClick(DialogInterface dialog, int which) {
  35. finish();
  36. }
  37. })
  38. .show();
  39. }
  40. else
  41. {
  42. //Webview stuff
  43. webview = findViewById(R.id.webView);
  44. webview.getSettings().setJavaScriptEnabled(true);
  45. webview.getSettings().setAllowFileAccess(true);
  46. webview.getSettings().setAllowFileAccess(true);
  47. webview.getSettings().setAllowFileAccessFromFileURLs(true);
  48. webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
  49. webview.setWebChromeClient(new WebChromeClient() {
  50. public boolean onShowFileChooser(WebView webView, ValueCallback&lt;Uri[]&gt; filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
  51. // Handle file upload
  52. return true;
  53. }
  54. });
  55. webview.setDownloadListener(new DownloadListener() {
  56. public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
  57. // Handle file download
  58. }
  59. });
  60. webview.setWebViewClient(new WebViewClient() {
  61. public boolean shouldOverrideUrlLoading(WebView webView, String url) {
  62. if (url.endsWith(&quot;.pdf&quot;)) {
  63. // Handle PDF file download
  64. return true;
  65. }
  66. // Handle other types of file downloads
  67. return false;
  68. }
  69. });
  70. webview.loadUrl(&quot;xyz.com/&quot;);
  71. webview.getSettings().setDomStorageEnabled(true);
  72. webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
  73. webview.loadUrl(websiteURL);
  74. webview.setWebViewClient(new WebViewClientDemo());
  75. webview.setWebChromeClient(new WebChromeClient() {
  76. @Override
  77. public boolean onShowFileChooser(WebView webView, ValueCallback&lt;Uri[]&gt; filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
  78. // Handle file upload
  79. return true;
  80. }
  81. });
  82. }
  83. }
  84. private class WebViewClientDemo extends WebViewClient {
  85. @Override
  86. //Keep webview in app when clicking links
  87. public boolean shouldOverrideUrlLoading(WebView view, String url) {
  88. if (url.startsWith(&quot;http:&quot;) || url.startsWith(&quot;https:&quot;)) {
  89. view.loadUrl(url);
  90. return true;
  91. } else {
  92. //Handle internal links
  93. view.loadUrl(websiteURL + url);
  94. return true;
  95. }
  96. }
  97. }
  98. @Override
  99. public void onBackPressed() { //if user presses the back button do this
  100. if (webview.isFocused() &amp;&amp; webview.canGoBack()) { //check if in webview and the user can go back
  101. webview.goBack(); //go back in webview
  102. } else { //do this if the webview cannot go back any further
  103. new AlertDialog.Builder(this) //alert the person knowing they are about to close
  104. .setTitle(&quot;EXIT&quot;)
  105. .setMessage(&quot;Are you sure. You want to close this app?&quot;)
  106. .setPositiveButton(&quot;Yes&quot;, new DialogInterface.OnClickListener() {
  107. @Override
  108. public void onClick(DialogInterface dialog, int which) {
  109. finish();
  110. }
  111. })
  112. .setNegativeButton(&quot;No&quot;, null)
  113. .show();
  114. }
  115. }
  116. }
  117. class CheckNetwork {
  118. private static final String TAG = CheckNetwork.class.getSimpleName();
  119. public static boolean isInternetAvailable(Context context)
  120. {
  121. NetworkInfo info = (NetworkInfo) ((ConnectivityManager)
  122. context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
  123. if (info == null)
  124. {
  125. Log.d(TAG,&quot;no internet connection&quot;);
  126. return false;
  127. }
  128. else
  129. {
  130. if(info.isConnected())
  131. {
  132. Log.d(TAG,&quot; internet connection available...&quot;);
  133. return true;
  134. }
  135. else
  136. {
  137. Log.d(TAG,&quot; internet connection&quot;);
  138. return true;
  139. }
  140. }
  141. }
  142. private class WebViewClientDemo extends WebViewClient {
  143. @Override
  144. //Keep webview in app when clicking links
  145. public boolean shouldOverrideUrlLoading(WebView view, String url) {
  146. view.loadUrl(url);
  147. return true;
  148. }
  149. @Override
  150. public void onPageFinished(WebView view, String url) {
  151. super.onPageFinished(view, url);
  152. // Enable full screen for embedded items
  153. view.loadUrl(&quot;javascript:(function() { &quot; +
  154. &quot;var videos = document.getElementsByTagName(&#39;video&#39;); &quot; +
  155. &quot;for(var i=0;i&lt;videos.length;i++) { &quot; +
  156. &quot;videos[i].setAttribute(&#39;webkit-playsinline&#39;, &#39;&#39;); &quot; +
  157. &quot;videos[i].setAttribute(&#39;playsinline&#39;, &#39;&#39;); &quot; +
  158. &quot;videos[i].setAttribute(&#39;controls&#39;, &#39;&#39;); &quot; +
  159. &quot;videos[i].setAttribute(&#39;style&#39;, &#39;max-width:100%; height:auto;&#39;); &quot; +
  160. &quot;}&quot; +
  161. &quot;var iframes = document.getElementsByTagName(&#39;iframe&#39;);&quot; +
  162. &quot;for(var i=0;i&lt;iframes.length;i++){&quot; +
  163. &quot;if(iframes[i].src.includes(&#39;youtube&#39;) || iframes[i].src.includes(&#39;vimeo&#39;)) {&quot; +
  164. &quot;iframes[i].setAttribute(&#39;frameborder&#39;, &#39;0&#39;);&quot; +
  165. &quot;iframes[i].setAttribute(&#39;allowfullscreen&#39;, &#39;&#39;);&quot; +
  166. &quot;iframes[i].setAttribute(&#39;webkitallowfullscreen&#39;, &#39;&#39;);&quot; +
  167. &quot;iframes[i].setAttribute(&#39;mozallowfullscreen&#39;, &#39;&#39;);&quot; +
  168. &quot;iframes[i].setAttribute(&#39;style&#39;, &#39;width:100%; height:100%;&#39;);&quot; +
  169. &quot;}&quot; +
  170. &quot;}&quot; +
  171. &quot;})()&quot;);
  172. }
  173. }
  174. }
  175. `

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">

  1. &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;
  2. &lt;uses-permission android:name=&quot;android.permission.ACCESS_NETWORK_STATE&quot; /&gt;
  3. &lt;uses-permission android:name=&quot;android.permission.CAMERA&quot; /&gt;
  4. &lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;
  5. &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot;/&gt;
  6. &lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot;/&gt;
  7. &lt;application
  8. android:usesCleartextTraffic=&quot;true&quot;
  9. android:allowBackup=&quot;true&quot;
  10. android:dataExtractionRules=&quot;@xml/data_extraction_rules&quot;
  11. android:fullBackupContent=&quot;@xml/backup_rules&quot;
  12. android:icon=&quot;@drawable/ic_launcher_foreground&quot;
  13. android:label=&quot;@string/app_name&quot;
  14. android:supportsRtl=&quot;true&quot;
  15. android:theme=&quot;@style/Theme.EprepareAcademy2O&quot;
  16. tools:targetApi=&quot;31&quot;&gt;
  17. &lt;activity
  18. android:name=&quot;.MainActivity&quot;
  19. android:exported=&quot;false&quot; /&gt;
  20. &lt;activity
  21. android:name=&quot;.SplashActivity&quot;
  22. android:exported=&quot;true&quot;&gt;
  23. &lt;intent-filter&gt;
  24. &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
  25. &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
  26. &lt;/intent-filter&gt;
  27. &lt;/activity&gt;
  28. &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时,我遇到了相同的问题,它无法打开存储,所以我在清单文件中添加了权限:

  1. <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
  2. <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" />
  3. <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 :

  1. uses-permission android:name= android.permission.READ_MEDIA_IMAGES
  2. uses-permission android:name= android.permission.READ_MEDIA_VIDEO
  3. 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:

确定