I am implementing a Web view to load a home page of a user after logging in. The web view consists of both file upload and download links.
I have searched stackoverflow for info on how to implement this, and came across some useful links, which helped me to meet my requirements up to some level. The problem I'm facing right now is that my file upload is not working for Android versions less than 5.0; for versions above 5.0, it seems to be working and the file chooser(browser) seems to pop up as soon as I click and upload button inside the web view. But there seems to be no action at all for versions less than 5.0.
I have only little experience working in Android, and this is the first time I'm using web view in a project. Also, this is my first question on stack overflow, so kindly excuse any mistakes in my question. Thanks in advance to whoever provides some help in arriving at my solution. Some explanation would always be appreciated.
Pasting my sample code below:
/**
* Settings for WebView & Loading webView from URL
*/
WebSettings webSettings = webView.getSettings();
webSettings.setLoadWithOverviewMode(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setUseWideViewPort(true);
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccess(true);
webSettings.setAllowContentAccess(true);
dialog = ProgressDialog.show(this, "Loading", "Please wait...", true);
dialog.setCancelable(true);
/**
* Checking device release version
*/
Log.d("ReleaseVersion", "=" + androidOS);
if (androidOS == 16) {
fourBoolean = true;
}
if (!fourBoolean) {
if (androidOS > 10 && androidOS < 21) {
firstBoolean = true;
} else if (androidOS >= 21) {
fiveBoolean = true;
}
}
/**
* fourBoolean gives TRUE if Target SDK version is 4.1
* firstBoolean gives TRUE if Target SDK version is 3.0+ (till 5.0, except 4.1)
* fiveBoolean gives TRUE if Target SDK version is 5.0+
*/
Log.d("ReleaseVersionFlags", "=" + "fourBoolean" + "=" + fourBoolean);
Log.d("ReleaseVersionFlags", "=" + "firstBoolean" + "=" + firstBoolean);
Log.d("ReleaseVersionFlags", "=" + "fiveBoolean" + "=" + fiveBoolean);
/**
* Method for uploading files to WebView (based on Target SDK version)
*/
if (fourBoolean) {
Log.d("ReleaseVersionStatus", "=" + "4.1");
webView.setWebChromeClient(new WebChromeClient() {
//For Android 4.1 only
protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
Log.d("ReleaseVersionInside", "=" + "inside 4.1 ONE");
mUploadMessage = uploadMsg;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "File Browser"), FILECHOOSER_RESULTCODE);
}
protected void openFileChooser(ValueCallback<Uri> uploadMsg) {
Log.d("ReleaseVersionInside", "=" + "inside 4.1 TWO");
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
}
});
}
if (firstBoolean) {
Log.d("ReleaseVersionStatus", "=" + "3.0+");
webView.setWebChromeClient(new WebChromeClient() {
// For 3.0+ Devices (Start)
// onActivityResult attached before constructor
protected void openFileChooser(ValueCallback uploadMsg, String acceptType) {
Log.d("ReleaseVersionInside", "=" + "inside 3.0");
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
}
});
}
if (fiveBoolean) {
Log.d("ReleaseVersionStatus", "=" + "5.0+");
webView.setWebChromeClient(new WebChromeClient() {
// For Lollipop 5.0+ Devices
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
Log.d("ReleaseVersionInside", "=" + "inside 5.0");
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
intent = fileChooserParams.createIntent();
}
try {
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e) {
uploadMessage = null;
Toast.makeText(getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
});
}
/**
* Override method to get result from FileChooser activity (File Upload)
*
* @param requestCode
* @param resultCode
* @param intent
*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode == REQUEST_SELECT_FILE) {
if (uploadMessage == null)
return;
uploadMessage.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
uploadMessage = null;
}
} else if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage)
return;
// Use MainActivity.RESULT_OK if you're implementing WebView inside Fragment
// Use RESULT_OK only if you're implementing WebView inside an Activity
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
} else
Toast.makeText(getApplicationContext(), "Failed to Upload Image", Toast.LENGTH_LONG).show();
}
This is the code which I am using for file download (I'm just pasting it, in case anyone might find it useful). Any modifications in the below code is appreciated.
/**
* Method for downloading files from WebView
*/
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));
Log.d("DownloadURL", "=" + url);
if (url.endsWith(".pdf")) {
Log.d("DownloadURLMime", "=" + "application/" + FilenameUtils.getExtension(url));
request.setMimeType("application/" + FilenameUtils.getExtension(url));
} else {
Log.d("DownloadURLMime", "=" + mimeType);
request.setMimeType(mimeType);
}
String cookies = CookieManager.getInstance().getCookie(url);
request.addRequestHeader("cookie", cookies);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("APP_NAME");
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...", Toast.LENGTH_SHORT).show();
}
});
If I need to provide any additional info, just comment and I'll post it here.
This is a code which i am using for upload image and pdf you can try it