Advertisement
PepeOreja

Untitled

Dec 23rd, 2022
722
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.61 KB | None | 0 0
  1. package com.exampleapp;
  2.  
  3. import androidx.activity.result.ActivityResultCallback;
  4. import androidx.activity.result.ActivityResultLauncher;
  5. import androidx.activity.result.contract.ActivityResultContracts;
  6. import androidx.appcompat.app.AppCompatActivity;
  7. import androidx.core.content.ContextCompat;
  8.  
  9. import android.Manifest;
  10. import android.app.Activity;
  11. import android.app.DownloadManager;
  12. import android.content.Context;
  13. import android.content.Intent;
  14. import android.content.pm.PackageManager;
  15. import android.graphics.Bitmap;
  16. import android.net.Uri;
  17. import android.os.Build;
  18. import android.os.Bundle;
  19. import android.os.Environment;
  20. import android.webkit.CookieManager;
  21. import android.webkit.DownloadListener;
  22. import android.webkit.GeolocationPermissions;
  23. import android.webkit.URLUtil;
  24. import android.webkit.ValueCallback;
  25. import android.webkit.WebChromeClient;
  26. import android.webkit.WebResourceRequest;
  27. import android.webkit.WebSettings;
  28. import android.webkit.WebView;
  29. import android.webkit.WebViewClient;
  30. import android.widget.Toast;
  31.  
  32. import java.util.ArrayList;
  33. import java.util.List;
  34. import java.util.Map;
  35.  
  36.  
  37. import android.os.Parcelable;
  38. import android.provider.MediaStore;
  39. import android.util.Log;
  40.  
  41. import java.io.File;
  42. import java.io.IOException;
  43.  
  44.  
  45. public class MainActivity extends AppCompatActivity {
  46. ActivityResultLauncher<String[]> mPermissionResultLauncher;
  47. private boolean isReadPermissionGranted=false;
  48. private boolean isLocationPermissionGranted=false;
  49. WebView webView;
  50.  
  51. private static String file_type = "*/*";
  52. private String cam_file_data = null;
  53. private ValueCallback<Uri> file_data;
  54. private ValueCallback<Uri[]> file_path;
  55. private final static int file_req_code = 1;
  56.  
  57. public Context context;
  58.  
  59. private static final String TAG = MainActivity.class.getSimpleName();
  60.  
  61. private static final int FILECHOOSER_RESULTCODE = 1;
  62. private ValueCallback<Uri> mUploadMessage;
  63. private Uri mCapturedImageURI = null;
  64.  
  65. // the same for Android 5.0 methods only
  66. private ValueCallback<Uri[]> mFilePathCallback;
  67. private String mCameraPhotoPath;
  68.  
  69.  
  70. @Override
  71. protected void onCreate(Bundle savedInstanceState) {
  72. super.onCreate(savedInstanceState);
  73. setContentView(R.layout.activity_main);
  74. webView = findViewById(R.id.webview);
  75. webView.setWebViewClient(new WebViewClient());
  76. webView.loadUrl("Insert your page with file input");
  77.  
  78. webView.setWebChromeClient(new WebChromeClient() {
  79. public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
  80. callback.invoke(origin, true, false);
  81. }
  82. /*-- handling input[type="file"] requests for android API 21+ --*/
  83.  
  84.  
  85. // for Lollipop, all in one
  86. public boolean onShowFileChooser(
  87. WebView webView, ValueCallback<Uri[]> filePathCallback,
  88. WebChromeClient.FileChooserParams fileChooserParams) {
  89. if (mFilePathCallback != null) {
  90. mFilePathCallback.onReceiveValue(null);
  91. }
  92. mFilePathCallback = filePathCallback;
  93.  
  94. Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
  95. if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
  96.  
  97. // create the file where the photo should go
  98. File photoFile = null;
  99. try {
  100. photoFile = createImageFile();
  101. takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
  102. } catch (IOException ex) {
  103. // Error occurred while creating the File
  104. Log.e(TAG, "Unable to create Image File", ex);
  105. }
  106.  
  107. // continue only if the file was successfully created
  108. if (photoFile != null) {
  109. mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
  110. takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
  111. Uri.fromFile(photoFile));
  112. } else {
  113. takePictureIntent = null;
  114. }
  115. }
  116.  
  117. Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
  118. contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
  119. contentSelectionIntent.setType("image/*");
  120.  
  121. Intent[] intentArray;
  122. if (takePictureIntent != null) {
  123. intentArray = new Intent[]{takePictureIntent};
  124. } else {
  125. intentArray = new Intent[0];
  126. }
  127.  
  128. Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
  129. chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
  130. chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.image_chooser));
  131. chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
  132.  
  133. startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
  134.  
  135. return true;
  136. }
  137.  
  138. // creating image files (Lollipop only)
  139. private File createImageFile() throws IOException {
  140.  
  141. File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "DirectoryNameHere");
  142.  
  143. if (!imageStorageDir.exists()) {
  144. imageStorageDir.mkdirs();
  145. }
  146.  
  147. // create an image file name
  148. imageStorageDir = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
  149. return imageStorageDir;
  150. }
  151.  
  152. // openFileChooser for Android 3.0+
  153. public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
  154. mUploadMessage = uploadMsg;
  155.  
  156. try {
  157. File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "DirectoryNameHere");
  158.  
  159. if (!imageStorageDir.exists()) {
  160. imageStorageDir.mkdirs();
  161. }
  162.  
  163. File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
  164.  
  165. mCapturedImageURI = Uri.fromFile(file); // save to the private variable
  166.  
  167. final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
  168. captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
  169. // captureIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  170.  
  171. Intent i = new Intent(Intent.ACTION_GET_CONTENT);
  172. i.addCategory(Intent.CATEGORY_OPENABLE);
  173. i.setType("image/*");
  174.  
  175. Intent chooserIntent = Intent.createChooser(i, getString(R.string.image_chooser));
  176. chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
  177.  
  178. startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
  179. } catch (Exception e) {
  180. Toast.makeText(getBaseContext(), "Camera Exception:" + e, Toast.LENGTH_LONG).show();
  181. }
  182.  
  183. }
  184.  
  185. // openFileChooser for Android < 3.0
  186. public void openFileChooser(ValueCallback<Uri> uploadMsg) {
  187. openFileChooser(uploadMsg, "");
  188. }
  189.  
  190. // openFileChooser for other Android versions
  191. /* may not work on KitKat due to lack of implementation of openFileChooser() or onShowFileChooser()
  192. https://code.google.com/p/android/issues/detail?id=62220
  193. however newer versions of KitKat fixed it on some devices */
  194. public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
  195. openFileChooser(uploadMsg, acceptType);
  196. }
  197.  
  198. });
  199. WebSettings webSettings = webView.getSettings();
  200. webSettings.setJavaScriptEnabled(true);
  201. webSettings.setAllowContentAccess(true);
  202. webSettings.setAllowFileAccess(true);
  203. webSettings.setAllowFileAccessFromFileURLs(true);
  204. webSettings.setAllowUniversalAccessFromFileURLs(true);
  205. webSettings.setUseWideViewPort(true);
  206. webSettings.setDomStorageEnabled(true);
  207. mPermissionResultLauncher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), new ActivityResultCallback<Map<String, Boolean>>() {
  208. @Override
  209. public void onActivityResult(Map<String, Boolean> result) {
  210. if(result.get(Manifest.permission.READ_EXTERNAL_STORAGE) !=null){
  211. isReadPermissionGranted = result.get(Manifest.permission.READ_EXTERNAL_STORAGE);
  212. }
  213. if(result.get(Manifest.permission.ACCESS_FINE_LOCATION) !=null){
  214. isLocationPermissionGranted = result.get(Manifest.permission.ACCESS_FINE_LOCATION);
  215. }
  216. }
  217.  
  218. });
  219. webView.setDownloadListener(new DownloadListener()
  220. {
  221.  
  222. @Override
  223.  
  224.  
  225. public void onDownloadStart(String url, String userAgent,
  226. String contentDisposition, String mimeType,
  227. long contentLength) {
  228.  
  229. DownloadManager.Request request = new DownloadManager.Request(
  230. Uri.parse(url));
  231.  
  232.  
  233. request.setMimeType(mimeType);
  234.  
  235.  
  236. String cookies = CookieManager.getInstance().getCookie(url);
  237.  
  238.  
  239. request.addRequestHeader("cookie", cookies);
  240.  
  241.  
  242. request.addRequestHeader("User-Agent", userAgent);
  243.  
  244.  
  245. request.setDescription("Downloading file...");
  246.  
  247.  
  248. request.setTitle(URLUtil.guessFileName(url, contentDisposition,
  249. mimeType));
  250.  
  251.  
  252. request.allowScanningByMediaScanner();
  253.  
  254.  
  255. request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
  256. request.setDestinationInExternalPublicDir(
  257. Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
  258. url, contentDisposition, mimeType));
  259. DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
  260. dm.enqueue(request);
  261. Toast.makeText(getApplicationContext(), "Downloading File",
  262. Toast.LENGTH_LONG).show();
  263. }});
  264.  
  265.  
  266. requestPermission();
  267. }
  268.  
  269. private class MywebClient extends WebViewClient{
  270. @Override
  271. public void onPageStarted(WebView view, String url, Bitmap favicon) {
  272. super.onPageStarted(view, url, favicon);
  273. }
  274. @Override
  275. public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
  276. return super.shouldOverrideUrlLoading(view, request);
  277. }
  278. }
  279.  
  280.  
  281. // return here when file selected from camera or from SD Card
  282. @Override
  283. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  284.  
  285. // code for all versions except of Lollipop
  286. if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
  287.  
  288. if (requestCode == FILECHOOSER_RESULTCODE) {
  289. if (null == this.mUploadMessage) {
  290. return;
  291. }
  292.  
  293. Uri result = null;
  294.  
  295. try {
  296. if (resultCode != RESULT_OK) {
  297. result = null;
  298. } else {
  299. // retrieve from the private variable if the intent is null
  300. result = data == null ? mCapturedImageURI : data.getData();
  301. }
  302. } catch (Exception e) {
  303. Toast.makeText(getApplicationContext(), "activity :" + e, Toast.LENGTH_LONG).show();
  304. }
  305.  
  306. mUploadMessage.onReceiveValue(result);
  307. mUploadMessage = null;
  308. }
  309.  
  310. } // end of code for all versions except of Lollipop
  311.  
  312. // start of code for Lollipop only
  313. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
  314.  
  315. if (requestCode != FILECHOOSER_RESULTCODE || mFilePathCallback == null) {
  316. super.onActivityResult(requestCode, resultCode, data);
  317. return;
  318. }
  319.  
  320. Uri[] results = null;
  321.  
  322. // check that the response is a good one
  323. if (resultCode == Activity.RESULT_OK) {
  324. if (data == null || data.getData() == null) {
  325. // If there is not data, then we may have taken a photo
  326. if (mCameraPhotoPath != null) {
  327. results = new Uri[]{Uri.parse(mCameraPhotoPath)};
  328. }
  329. } else {
  330. String dataString = data.getDataString();
  331. if (dataString != null) {
  332. results = new Uri[]{Uri.parse(dataString)};
  333. }
  334. }
  335. }
  336.  
  337. mFilePathCallback.onReceiveValue(results);
  338. mFilePathCallback = null;
  339.  
  340. } // end of code for Lollipop only
  341.  
  342. }
  343.  
  344.  
  345. @Override
  346. public void onBackPressed() {
  347. if(webView.isFocused() && webView.canGoBack())
  348. {
  349. webView.goBack();
  350. }else{
  351. super.onBackPressed();
  352. }
  353. }
  354.  
  355. private void requestPermission(){
  356.  
  357. isReadPermissionGranted = ContextCompat.checkSelfPermission(
  358. this,
  359. Manifest.permission.READ_EXTERNAL_STORAGE
  360. )== PackageManager.PERMISSION_GRANTED;
  361.  
  362. isLocationPermissionGranted = ContextCompat.checkSelfPermission(
  363. this,
  364. Manifest.permission.ACCESS_FINE_LOCATION
  365. )== PackageManager.PERMISSION_GRANTED;
  366.  
  367. List<String> permissionRequest= new ArrayList<String>();
  368.  
  369. if(!isLocationPermissionGranted)
  370. {
  371. permissionRequest.add(Manifest.permission.ACCESS_FINE_LOCATION);
  372. }
  373. if(!isReadPermissionGranted)
  374. {
  375. permissionRequest.add(Manifest.permission.READ_EXTERNAL_STORAGE);
  376. }
  377. if (!permissionRequest.isEmpty()){
  378. mPermissionResultLauncher.launch(permissionRequest.toArray(new String[0]));
  379. }
  380. }
  381. }
  382.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement