Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.exampleapp;
- import androidx.activity.result.ActivityResultCallback;
- import androidx.activity.result.ActivityResultLauncher;
- import androidx.activity.result.contract.ActivityResultContracts;
- import androidx.appcompat.app.AppCompatActivity;
- import androidx.core.content.ContextCompat;
- import android.Manifest;
- import android.app.Activity;
- import android.app.DownloadManager;
- import android.content.Context;
- import android.content.Intent;
- import android.content.pm.PackageManager;
- import android.graphics.Bitmap;
- import android.net.Uri;
- import android.os.Build;
- import android.os.Bundle;
- import android.os.Environment;
- import android.webkit.CookieManager;
- import android.webkit.DownloadListener;
- import android.webkit.GeolocationPermissions;
- import android.webkit.URLUtil;
- import android.webkit.ValueCallback;
- import android.webkit.WebChromeClient;
- import android.webkit.WebResourceRequest;
- import android.webkit.WebSettings;
- import android.webkit.WebView;
- import android.webkit.WebViewClient;
- import android.widget.Toast;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Map;
- import android.os.Parcelable;
- import android.provider.MediaStore;
- import android.util.Log;
- import java.io.File;
- import java.io.IOException;
- public class MainActivity extends AppCompatActivity {
- ActivityResultLauncher<String[]> mPermissionResultLauncher;
- private boolean isReadPermissionGranted=false;
- private boolean isLocationPermissionGranted=false;
- WebView webView;
- private static String file_type = "*/*";
- private String cam_file_data = null;
- private ValueCallback<Uri> file_data;
- private ValueCallback<Uri[]> file_path;
- private final static int file_req_code = 1;
- public Context context;
- private static final String TAG = MainActivity.class.getSimpleName();
- private static final int FILECHOOSER_RESULTCODE = 1;
- private ValueCallback<Uri> mUploadMessage;
- private Uri mCapturedImageURI = null;
- // the same for Android 5.0 methods only
- private ValueCallback<Uri[]> mFilePathCallback;
- private String mCameraPhotoPath;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- webView = findViewById(R.id.webview);
- webView.setWebViewClient(new WebViewClient());
- webView.loadUrl("Insert your page with file input");
- webView.setWebChromeClient(new WebChromeClient() {
- public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
- callback.invoke(origin, true, false);
- }
- /*-- handling input[type="file"] requests for android API 21+ --*/
- // for Lollipop, all in one
- public boolean onShowFileChooser(
- WebView webView, ValueCallback<Uri[]> filePathCallback,
- WebChromeClient.FileChooserParams fileChooserParams) {
- if (mFilePathCallback != null) {
- mFilePathCallback.onReceiveValue(null);
- }
- mFilePathCallback = filePathCallback;
- Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
- // create the file where the photo should go
- File photoFile = null;
- try {
- photoFile = createImageFile();
- takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
- } catch (IOException ex) {
- // Error occurred while creating the File
- Log.e(TAG, "Unable to create Image File", ex);
- }
- // continue only if the file was successfully created
- if (photoFile != null) {
- mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
- takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
- Uri.fromFile(photoFile));
- } else {
- takePictureIntent = null;
- }
- }
- Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
- contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
- contentSelectionIntent.setType("image/*");
- Intent[] intentArray;
- if (takePictureIntent != null) {
- intentArray = new Intent[]{takePictureIntent};
- } else {
- intentArray = new Intent[0];
- }
- Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
- chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
- chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.image_chooser));
- chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
- startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
- return true;
- }
- // creating image files (Lollipop only)
- private File createImageFile() throws IOException {
- File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "DirectoryNameHere");
- if (!imageStorageDir.exists()) {
- imageStorageDir.mkdirs();
- }
- // create an image file name
- imageStorageDir = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
- return imageStorageDir;
- }
- // openFileChooser for Android 3.0+
- public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
- mUploadMessage = uploadMsg;
- try {
- File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "DirectoryNameHere");
- if (!imageStorageDir.exists()) {
- imageStorageDir.mkdirs();
- }
- File file = new File(imageStorageDir + File.separator + "IMG_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
- mCapturedImageURI = Uri.fromFile(file); // save to the private variable
- final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
- captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
- // captureIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
- Intent i = new Intent(Intent.ACTION_GET_CONTENT);
- i.addCategory(Intent.CATEGORY_OPENABLE);
- i.setType("image/*");
- Intent chooserIntent = Intent.createChooser(i, getString(R.string.image_chooser));
- chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
- startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
- } catch (Exception e) {
- Toast.makeText(getBaseContext(), "Camera Exception:" + e, Toast.LENGTH_LONG).show();
- }
- }
- // openFileChooser for Android < 3.0
- public void openFileChooser(ValueCallback<Uri> uploadMsg) {
- openFileChooser(uploadMsg, "");
- }
- // openFileChooser for other Android versions
- /* may not work on KitKat due to lack of implementation of openFileChooser() or onShowFileChooser()
- https://code.google.com/p/android/issues/detail?id=62220
- however newer versions of KitKat fixed it on some devices */
- public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
- openFileChooser(uploadMsg, acceptType);
- }
- });
- WebSettings webSettings = webView.getSettings();
- webSettings.setJavaScriptEnabled(true);
- webSettings.setAllowContentAccess(true);
- webSettings.setAllowFileAccess(true);
- webSettings.setAllowFileAccessFromFileURLs(true);
- webSettings.setAllowUniversalAccessFromFileURLs(true);
- webSettings.setUseWideViewPort(true);
- webSettings.setDomStorageEnabled(true);
- mPermissionResultLauncher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), new ActivityResultCallback<Map<String, Boolean>>() {
- @Override
- public void onActivityResult(Map<String, Boolean> result) {
- if(result.get(Manifest.permission.READ_EXTERNAL_STORAGE) !=null){
- isReadPermissionGranted = result.get(Manifest.permission.READ_EXTERNAL_STORAGE);
- }
- if(result.get(Manifest.permission.ACCESS_FINE_LOCATION) !=null){
- isLocationPermissionGranted = result.get(Manifest.permission.ACCESS_FINE_LOCATION);
- }
- }
- });
- 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));
- request.setMimeType(mimeType);
- String cookies = CookieManager.getInstance().getCookie(url);
- request.addRequestHeader("cookie", cookies);
- request.addRequestHeader("User-Agent", userAgent);
- request.setDescription("Downloading file...");
- request.setTitle(URLUtil.guessFileName(url, contentDisposition,
- mimeType));
- request.allowScanningByMediaScanner();
- request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
- request.setDestinationInExternalPublicDir(
- Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(
- url, contentDisposition, mimeType));
- DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
- dm.enqueue(request);
- Toast.makeText(getApplicationContext(), "Downloading File",
- Toast.LENGTH_LONG).show();
- }});
- requestPermission();
- }
- private class MywebClient extends WebViewClient{
- @Override
- public void onPageStarted(WebView view, String url, Bitmap favicon) {
- super.onPageStarted(view, url, favicon);
- }
- @Override
- public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
- return super.shouldOverrideUrlLoading(view, request);
- }
- }
- // return here when file selected from camera or from SD Card
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- // code for all versions except of Lollipop
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
- if (requestCode == FILECHOOSER_RESULTCODE) {
- if (null == this.mUploadMessage) {
- return;
- }
- Uri result = null;
- try {
- if (resultCode != RESULT_OK) {
- result = null;
- } else {
- // retrieve from the private variable if the intent is null
- result = data == null ? mCapturedImageURI : data.getData();
- }
- } catch (Exception e) {
- Toast.makeText(getApplicationContext(), "activity :" + e, Toast.LENGTH_LONG).show();
- }
- mUploadMessage.onReceiveValue(result);
- mUploadMessage = null;
- }
- } // end of code for all versions except of Lollipop
- // start of code for Lollipop only
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
- if (requestCode != FILECHOOSER_RESULTCODE || mFilePathCallback == null) {
- super.onActivityResult(requestCode, resultCode, data);
- return;
- }
- Uri[] results = null;
- // check that the response is a good one
- if (resultCode == Activity.RESULT_OK) {
- if (data == null || data.getData() == null) {
- // If there is not data, then we may have taken a photo
- if (mCameraPhotoPath != null) {
- results = new Uri[]{Uri.parse(mCameraPhotoPath)};
- }
- } else {
- String dataString = data.getDataString();
- if (dataString != null) {
- results = new Uri[]{Uri.parse(dataString)};
- }
- }
- }
- mFilePathCallback.onReceiveValue(results);
- mFilePathCallback = null;
- } // end of code for Lollipop only
- }
- @Override
- public void onBackPressed() {
- if(webView.isFocused() && webView.canGoBack())
- {
- webView.goBack();
- }else{
- super.onBackPressed();
- }
- }
- private void requestPermission(){
- isReadPermissionGranted = ContextCompat.checkSelfPermission(
- this,
- Manifest.permission.READ_EXTERNAL_STORAGE
- )== PackageManager.PERMISSION_GRANTED;
- isLocationPermissionGranted = ContextCompat.checkSelfPermission(
- this,
- Manifest.permission.ACCESS_FINE_LOCATION
- )== PackageManager.PERMISSION_GRANTED;
- List<String> permissionRequest= new ArrayList<String>();
- if(!isLocationPermissionGranted)
- {
- permissionRequest.add(Manifest.permission.ACCESS_FINE_LOCATION);
- }
- if(!isReadPermissionGranted)
- {
- permissionRequest.add(Manifest.permission.READ_EXTERNAL_STORAGE);
- }
- if (!permissionRequest.isEmpty()){
- mPermissionResultLauncher.launch(permissionRequest.toArray(new String[0]));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement