WebView does not react after file chooser - android

I have created a WebView, which display webpage with Input type file. But after choosing file, my webview does not react to anything, only for objects outside of webView (refresh button). How can i fix it?
The problem occurs in android 4.1.2
My code:
package com.gymcourses.qiteq.pai16;
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.ActionBar;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.webkit.GeolocationPermissions;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
private final int SPLASH_DISPLAY_LENGTH = 1000;
private final static int FILECHOOSER_RESULTCODE=1;
ProgressBar progressBar;
public WebView webView;
private ValueCallback<Uri> mUploadMessage;
ImageView refreshBtn;
private ValueCallback<Uri[]> mFilePathCallback;
private Uri mCapturedImageURI = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (isNetworkConnected()) Log.v("INTERNET: ", "true");
else Log.v("INTERNET: ", "false;");
if (isNetworkConnected()) {
refreshBtn = (ImageView) findViewById(R.id.refreshBtn);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
refreshBtn.setVisibility(View.INVISIBLE);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
webView = (WebView) findViewById(R.id.webView);
webView.setVisibility(View.INVISIBLE);
webView.loadUrl("http://something.com");
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setGeolocationEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSaveFormData(false);
webView.getSettings().setSavePassword(false);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setGeolocationDatabasePath(getFilesDir().getPath());
WebChromeClient webChromeClient = new WebChromeClient(){
#Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
// callback.invoke(String origin, boolean allow, boolean remember);
callback.invoke(origin, true, false);
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), MainActivity.FILECHOOSER_RESULTCODE);
}
public boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams){
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), MainActivity.FILECHOOSER_RESULTCODE);
return false;
}
};
WebViewClient webViewClient = new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url){
progressBar.setVisibility(View.GONE);
webView.setVisibility(View.VISIBLE);
refreshBtn.setVisibility(View.VISIBLE);
}
};
webView.setWebChromeClient(webChromeClient);
webView.setWebViewClient(webViewClient);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 0);
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.alertDialogMessage))
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
public void refresh(View view){
webView.reload();
refreshBtn.setVisibility(View.INVISIBLE);
webView.setVisibility(View.INVISIBLE);
progressBar.setVisibility(View.VISIBLE);
}
public boolean isNetworkConnected(){
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
}

Try This Example adapt it with the new Version of API, check the new implementation of FileChooser.
public class WebViewActivity extends ActionBarActivity {
private final static int FILECHOOSER_RESULTCODE = 1;
private final static String url = "https://www.cs.tut.fi/~jkorpela/forms/file.html";
public static WebViewActivity _activity;
ProgressDialog progressBar;
ProgressBar progressBar1;
AlertDialog alertDialog;
boolean loadingFinished = true;
boolean redirect = false;
Menu menu;
WebView wv;
private ValueCallback<Uri> mUploadMessage;
private String TAG = "WebViewActivity";
public static boolean checkInternetConnection(Activity _activity) {
ConnectivityManager conMgr = (ConnectivityManager) _activity.getSystemService(Context.CONNECTIVITY_SERVICE);
return conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_activity = this;
wv = new WebView(this);
WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(true);
settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
settings.setSaveFormData(true);
settings.setSavePassword(true); // Not needed for API level 18 or greater (deprecated)
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
if (cookieManager.hasCookies()) {
Log.d(TAG, "has cookies");
} else {
Log.d(TAG, "has not cookies");
}
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
wv.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
wv.setWebChromeClient(new WebChromeClient() {
//The undocumented magic method override
//Eclipse will swear at you if you try to put #Override here
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
WebViewActivity.this.showAttachmentDialog(uploadMsg);
}
// For Android > 3.x
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
WebViewActivity.this.showAttachmentDialog(uploadMsg);
}
// For Android > 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
WebViewActivity.this.showAttachmentDialog(uploadMsg);
}
});
this.setContentView(wv);
if (checkInternetConnection(_activity) == true) {
if (savedInstanceState == null) {
wv.loadUrl(url );
} else
wv.loadUrl(url );
alertDialog = new AlertDialog.Builder(this, AlertDialog.THEME_HOLO_DARK).create();
alertDialog.setCancelable(true);
progressBar = ProgressDialog.show(WebViewActivity.this, getResources().getString(R.string.patientez),
getResources().getString(R.string.chargement));
progressBar.setCancelable(true);
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
wv.loadUrl(urlNewString);
return true;
}
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}
#Override
public void onPageFinished(WebView view, String url) {
Log.d(TAG, "onPageFinished");
//CookieSyncManager.getInstance().sync();
if (!redirect) {
loadingFinished = true;
}
if (loadingFinished && !redirect) {
//HIDE LOADING IT HAS FINISHED
if (progressBar != null && progressBar.isShowing()) {
progressBar.hide();
}
} else {
redirect = false;
}
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
loadingFinished = false;
progressBar.show();
}
});
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(_activity);
builder.setTitle(R.string.configDoc);
builder.setMessage(R.string.pro_refresh)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), ProActivity.class);
//intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
// to know if upload is finished
private void showAttachmentDialog(ValueCallback<Uri> uploadMsg) {
this.mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
this.startActivityForResult(Intent.createChooser(i, "Choose type of attachment"), FILECHOOSER_RESULTCODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
this.mUploadMessage.onReceiveValue(result);
this.mUploadMessage = null;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && wv.canGoBack()) {
//if Back key pressed and webview can navigate to previous page
wv.goBack();
// go back to previous page
return true;
} else {
finish();
// finish the activity
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed() {
// Do Some thing Here
// this.finish();
super.onBackPressed();
}
#Override
protected void onDestroy() {
super.onDestroy(); //To change body of overridden methods use File | Settings | File Templates.
}
#Override
protected void onResume() {
super.onResume(); //To change body of overridden methods use File | Settings | File Templates.
}
#Override
protected void onPause() {
super.onPause(); //To change body of overridden methods use File | Settings | File Templates.
}
#Override
protected void onStop() {
super.onStop(); //To change body of overridden methods use File | Settings | File Templates.
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
} }

Try to implement your onActivityResult. the important is the call of onReceiveValue() method, you can test this with an example in githhub
https://github.com/henrychuangtw/Kitkat-WebView. this is an exampleFor an ActivityResult:
private ValueCallback mFIlePathCallback;
private ValueCallback mFIlePathCallbackLollipop;
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
Log.d(TAG, "onActivityResult");
if ((requestCode == mFilechooserResultcode) && (resultCode == RESULT_OK)) {
if ((mFIlePathCallback == null) && (mFIlePathCallbackLollipop == null)) {
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//lollipop +
String dataString = intent.getDataString();
if (dataString != null) {
Uri[] result = new Uri[]{Uri.parse(dataString)};
mFIlePathCallbackLollipop.onReceiveValue(result);
mFIlePathCallbackLollipop = null;
}
} else {
//kitkat -
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
mFIlePathCallback.onReceiveValue(result);
mFIlePathCallback = null;
}
}
}

Related

ProgressDialog disapears as soon as file is uploaded in Webview

I am having webview code which display processing circle while going from one page to another.
Code works very well until we upload some file. As soon as file is uploaded user redirects to another page. After this processing circle which is displayed from one page to another is not displayed at all.
I tried googling on this topic but no use, looks like this is new issue on web lol.
Also there's another issue regarding javascript alert box. Instead of given title it displays "The page at http://example.com says:". tried solutions on web but no use...
It would be very helpful if someone could point out underlying issues here. Thanks...
Below is my code:
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.google.firebase.iid.FirebaseInstanceId;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import static android.content.ContentValues.TAG;
public class MainActivity extends Activity {
public static WebView mWebview;
private android.content.Context Context;
private static String getIntentValue = null;
public static SharedPreferences sharedPreferences;
private ProgressDialog mProgressDialog;
private String mCM;
private ValueCallback<Uri> mUM;
private ValueCallback<Uri[]> mUMA;
private final static int FCR=1;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
mWebview.setWebViewClient(new Callback());
if(Build.VERSION.SDK_INT >= 21){
Uri[] results = null;
//Check if response is positive
if(resultCode== Activity.RESULT_OK){
if(requestCode == FCR){
if(null == mUMA){
return;
}
if(intent == null){
//Capture Photo if no image available
if(mCM != null){
results = new Uri[]{Uri.parse(mCM)};
}
}else{
String dataString = intent.getDataString();
if(dataString != null){
results = new Uri[]{Uri.parse(dataString)};
}
}
}
}
mUMA.onReceiveValue(results);
mUMA = null;
}else{
if(requestCode == FCR){
if(null == mUM) return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
mUM.onReceiveValue(result);
mUM = null;
}
}
}
private void enableHTML5AppCache() {
mWebview.getSettings().setDomStorageEnabled(true);
mWebview.getSettings().setAppCachePath("/data/data/" + getPackageName() + "/cache");
mWebview.getSettings().setAppCacheEnabled(true);
mWebview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context = this;
String regId = FirebaseInstanceId.getInstance().getToken();
getIntentValue = getIntent().getStringExtra("value");
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
if (!DetectConnection.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "No Internet Connection!", Toast.LENGTH_LONG).show();
// finish(); //Calling this method to close this activity when internet is not available.
} else {
mWebview = (WebView) findViewById(R.id.webview1);
WebSettings webSettings = mWebview.getSettings();
mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.setWebChromeClient(new WebChromeClient());
mWebview.setWebChromeClient(new JsPopupWebViewChrome()); mWebview.setWebViewClient(new CustomWebViewClient());
//improve WebView Performance
mWebview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mWebview.getSettings().setAppCacheEnabled(true);
mWebview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
if(Build.VERSION.SDK_INT >= 21){
webSettings.setMixedContentMode(0);
mWebview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}else if(Build.VERSION.SDK_INT >= 19){
mWebview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}else if(Build.VERSION.SDK_INT < 19){
mWebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
if(Build.VERSION.SDK_INT >=23 && (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA}, 1);
}
mWebview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setAllowFileAccess(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
enableHTML5AppCache();
// progress dialog
mProgressDialog = new ProgressDialog(Context);
if (sharedPreferences.getBoolean("isKeyGenerated", true)) {
if (getIntentValue != null) {
mWebview.loadUrl("http://example.com");
getIntentValue = null;
} else {
mWebview.loadUrl("http://example.com");
}
}
}
mWebview.setWebChromeClient(new WebChromeClient(){
//For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg){
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FCR);
}
// For Android 3.0+, above method not supported in some android 3+ versions, in such case we use this
public void openFileChooser(ValueCallback uploadMsg, String acceptType){
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FCR);
}
//For Android 4.1+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), MainActivity.FCR);
}
//For Android 5.0+
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams){
if(mUMA != null){
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null){
File photoFile = null;
try{
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
}catch(IOException ex){
Log.e(TAG, "Image file creation failed", ex);
}
if(photoFile != null){
mCM = "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("*/*");
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, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FCR);
return true;
}
});
}
private class JsPopupWebViewChrome extends WebChromeClient {
#Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder b = new AlertDialog.Builder(view.getContext())
.setTitle("ALERT!")
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
});
b.show();
// Indicate that we're handling this manually
return true;
}
}
public class Callback extends WebViewClient{
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
}
}
// Create an image file
private File createImageFile() throws IOException {
#SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "img_"+timeStamp+"_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return File.createTempFile(imageFileName,".jpg",storageDir);
}
// Function to load all URLs in same webview
private class CustomWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!DetectConnection.checkInternetConnection(Context)) {
if (url.contains("http://example.com")){ // Log.d("offline url", url);
view.loadUrl(url);
}else {
Toast.makeText(Context, "No Internet Connection!", Toast.LENGTH_SHORT).show(); // Log.d("other urls", url);
}
} else if (url.contains(".pdf")) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
//on page started, show loading page
mProgressDialog.setCancelable(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.show();
}
#Override
public void onPageFinished(WebView view, String url)
{
String currentPage= mWebview.getUrl();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("currentpage",currentPage);
editor.commit();
//after loading page, remove loading page
// TODO Auto-generated method stub
super.onPageFinished(view, url);
mProgressDialog.dismiss();
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) { // Log.e(TAG," Error occured while loading the web page at Url"+ failingUrl+"." +description); //
Intent intent = new Intent(MainActivity.this, noconnection.class);
intent.putExtra("a", "mainactivity is source");
startActivity(intent); //
Toast.makeText(getApplicationContext(), "Error occured, please check network connectivity", Toast.LENGTH_SHORT).show();
// super.onReceivedError(view, errorCode, description, failingUrl);
}
}
#Override
public void onBackPressed() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String currenturl = sharedPreferences.getString("currentpage", null);
mWebview.requestFocus();
if (!DetectConnection.checkInternetConnection(Context)) {
mWebview.loadUrl("http://example.com");
}else if (currenturl.contains("http://example.com")){
moveTaskToBack(true);
}else if(currenturl.contains("http://example.com")){
mWebview.loadUrl("http://example.com");
}else if(currenturl.contains("http://example.com")){ mWebview.loadUrl("http://example.com"); }else{
mWebview.goBack();
}
if (mWebview.canGoBack()) {
if (!DetectConnection.checkInternetConnection(Context)) {
Toast.makeText(Context, "No Internet Connection!", Toast.LENGTH_SHORT).show();
}
}
}
public static void loadUrl(String key) {
if (getIntentValue != null) {
mWebview.loadUrl("http://example.com");
getIntentValue = null;
} else {
mWebview.loadUrl("http://example.com");
}
}
public static void reLoad() {
mWebview.reload();
}
#Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
} }
maybe you should override WebChromeClient's onProgressChanged and control dialog in it.

choose files dont work on the phone using webview

I have a button choose files in website, when you press the button on your computer it works and when you press the button on the phone does not work what solution, the site shows using WebView
mywebsite = (WebView)findViewById(R.id.mywebsite);
pd_loading = (ProgressBar)findViewById(R.id.pd_loading);
mywebsite.getSettings().setLoadsImagesAutomatically(true);
mywebsite.getSettings().setJavaScriptEnabled(true);
mywebsite.setWebViewClient(new WebViewClient());
mywebsite.loadUrl(Information.URL_Home);
mywebsite.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view ,String url)
{
pd_loading.setVisibility(View.GONE);
mywebsite.setVisibility(View.VISIBLE);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
Toasty.error(Home.this,"",Toast.LENGTH_SHORT,true).show();
}
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(Intent.createChooser(i, "File Chooser"), 101);
mUploadMessage = uploadMsg;
}
// For Android > 4.1 - undocumented method
#SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, "");
}
// For Android > 5.0
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
startActivityForResult(fileChooserParams.createIntent(), 101);
return true;
}
});
onActivittyResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
switch (requestCode) {
case 101:
if (resultCode == RESULT_OK) {
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
if (mUploadMessage != null) {
mUploadMessage.onReceiveValue(result);
} else if (afterLolipop != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
afterLolipop.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
afterLolipop = null;
}
}
mUploadMessage = null;
}
}
}
these codes don't work I just want to choose a picture of a computer I hope help me thanks
When I faced a similar kind of issue, I have made use of setWebChromeClient() method found from this souce.
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
import org.apache.http.util.EncodingUtils;
public class BrowserScreen extends Activity {
private WebView webView;
private String url = "url";
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.browser_activity);
initFields();
setListeners();
}
public void initFields() {
// TODO Auto-generated method stub
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setAllowFileAccess(true);
}
public void setListeners() {
// TODO Auto-generated method stub
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webView.loadUrl("about:blank");
view.clearHistory();
}
});
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
}
//The undocumented magic method override
//Eclipse will swear at you if you try to put #Override here
// For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
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);
}
// For Android 3.0+
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
//For Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
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);
}
});
webView.loadUrl(url);
final MyJavaScriptInterface myJavaScriptInterface
= new MyJavaScriptInterface(this);
webView.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (webView.canGoBack() == true) {
webView.goBack();
} else {
super.onBackPressed();
}
}
public class MyJavaScriptInterface {
Context mContext;
MyJavaScriptInterface(Context c) {
mContext = c;
}
#JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
// webView.loadUrl("javascript:document.getElementById(\"Button3\").innerHTML = \"bye\";");
}
#JavascriptInterface
public void openAndroidDialog() {
AlertDialog.Builder myDialog
= new AlertDialog.Builder(BrowserScreen.this);
myDialog.setTitle("DANGER!");
myDialog.setMessage("You can do what you want!");
myDialog.setPositiveButton("ON", null);
myDialog.show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage) return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
}

<Input type="file"> not working in my WebView

I develop Fragment WebView Application.
I use upload code in Fragment WebView. When I click <input type="file">
it is active nothing. logcat show only this warning
05-22 15:59:39.749 31611-31611/kr.nubiz.comn W/cr_Ime: updateState: type [0->0], flags [0], show [false],
How can I solve this problem?
WebView - Fragment
private void initLayout() {
handler = new Handler();
webView = (android.webkit.WebView) rootView.findViewById(R.id.webview);
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setSupportMultipleWindows(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.addJavascriptInterface(new AndroidBridge(), "android");
webView.setDrawingCacheEnabled(false);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedHttpAuthRequest(android.webkit.WebView view, HttpAuthHandler handler, String host, String realm) {
super.onReceivedHttpAuthRequest(view, handler, host, realm);
}
#Override
public boolean shouldOverrideUrlLoading(android.webkit.WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
#Override
public void onPageFinished(android.webkit.WebView view, String url) {
webView.scrollTo(0, 0);
Integer menu = 0;
if (url.contains("index")) {
menu = 0;
} else if (url.contains("login")) {
menu = 1;
} else if (url.contains("myPage")) {
menu = 2;
} else if (url.contains("community")) {
menu = 3;
} else if (url.contains("debate")) {
menu = 4;
} else if (url.contains("vote")) {
menu = 5;
} else if (url.contains("guide")) {
menu = 6;
} else if (url.contains("board")) {
menu = 7;
} else if (url.contains("privacy")) {
menu = 8;
} else if (url.contains("Term")) {
menu = 9;
}
super.onPageFinished(view, url);
}
});
webView.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onCreateWindow(android.webkit.WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
android.webkit.WebView newWebView = new android.webkit.WebView(getActivity());
newWebView.getSettings().setJavaScriptEnabled(true);
newWebView.getSettings().setSupportZoom(false);
newWebView.getSettings().setBuiltInZoomControls(true);
newWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
newWebView.getSettings().setSupportMultipleWindows(true);
newWebView.getSettings().setBuiltInZoomControls(true);
newWebView.getSettings().setLoadWithOverviewMode(true);
newWebView.getSettings().setUseWideViewPort(true);
newWebView.getSettings().setAllowFileAccess(true);
newWebView.getSettings().setAllowContentAccess(true);
newWebView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
view.addView(newWebView);
android.webkit.WebView.WebViewTransport transport = (android.webkit.WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
newWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(android.webkit.WebView view, String url) {
if (url.startsWith("tel:") || url.startsWith("sms:")) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
} else {
view.loadUrl(url);
return true;
}
}
#Override
public void onPageFinished(android.webkit.WebView view, String url) {
webView.scrollTo(0, 0);
super.onPageFinished(view, url);
}
});
newWebView.setWebChromeClient(this);
return true;
}
// For 3.0+ Devices (Start)
// onActivityResult attached before constructor
protected void openFileChooser(ValueCallback uploadMsg, String acceptType) {
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);
}
// For Lollipop 5.0+ Devices
public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
intent = fileChooserParams.createIntent();
}
try {
startActivityForResult(intent, REQUEST_SELECT_FILE);
} catch (ActivityNotFoundException e) {
uploadMessage = null;
Toast.makeText(getActivity().getApplicationContext(), "Cannot Open File Chooser", Toast.LENGTH_LONG).show();
return false;
}
return true;
}
//For Android 4.1 only
protected void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
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) {
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);
}
#Override
public void onCloseWindow(android.webkit.WebView window) {
webView.removeAllViews();
webView.removeView(window);
super.onCloseWindow(window);
}
});
webView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
try {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimetype);
request.addRequestHeader("User_Agent", userAgent);
request.setDescription("Downloading file");
String fileName = contentDisposition.replace("inline; filename=", "");
fileName = fileName.replace("\"", "");
fileName = fileName.replace("attachment;", "");
fileName = fileName.replace("filename=", "");
fileName = fileName.replace(";", "");
fileName = fileName.replace(" ", "");
request.setTitle(fileName);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getActivity().getApplicationContext(), "파일 다운로드", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(getActivity(), "첨부파일을 다운 받기 위해\n동의가 필요합니다.", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 110);
} else {
Toast.makeText(getActivity(), "첨부파일을 다운 받기 위해\n동의가 필요합니다.", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 110);
}
}
}
}
});
webView.getSettings().setBuiltInZoomControls(true);
webView.setOnTouchListener(this);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
} else {
webView.getSettings().setLoadWithOverviewMode(true);
}
startWebView(url);
}
public void startWebView(String url) {
webView.onResume();
webView.loadUrl(url);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage) return;
Uri result = data == null || resultCode != RESULT_OK ? null :
data.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
Manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
I solve this problem. So It is self answer. I hope It is helpful other developers.
WebView-Fragment
package kr.nubiz.comn;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.DownloadListener;
import android.webkit.HttpAuthHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.Toast;
import com.facebook.CallbackManager;
import com.facebook.share.widget.ShareDialog;
import com.kakao.kakaolink.KakaoLink;
import com.kakao.kakaolink.KakaoTalkLinkMessageBuilder;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import kr.nubiz.comn.Activity.MainActivity;
import kr.nubiz.comn.Util.ConnectServer;
import static android.app.Activity.RESULT_OK;
/**
* Created by NUBIZ_APP on 2017-05-24.
*/
public class WebViews extends Fragment {
private View rootView;
private android.webkit.WebView webView;
private Fragment mContent;
private FrameLayout frameLayout, frame;
private ConnectServer connectServer;
private String url;
private String hasSub;
private HashMap<String, String> user_Info;
private HashMap<String, String> device_Info;
private String able_Push;
private String device_Id;
private int startY = 0;
private ImageButton btn_OpenMenu;
private HashMap<String, String> hasSubs;
private Handler handler;
private ValueCallback<Uri> mUploadMessage;
public ValueCallback<Uri[]> uploadMessage;
public static final int REQUEST_SELECT_FILE = 100;
private final static int FILECHOOSER_RESULTCODE = 1;
public static final String INTENT_PROTOCOL_START = "intent:";
public static final String INTENT_PROTOCOL_INTENT = "#Intent;";
public static final String INTENT_PROTOCOL_END = ";end;";
public static final String GOOGLE_PLAY_STORE_PREFIX = "market://details?id=";
private CallbackManager callbackManager;
private ShareDialog shareDialog;
private KakaoTalkLinkMessageBuilder kakaoTalkLinkMessageBuilder;
private KakaoLink kakaoLink;
private static final String TAG = MainActivity.class.getSimpleName();
private String mCM;
private ValueCallback<Uri> mUM;
private ValueCallback<Uri[]> mUMA;
private final static int FCR = 1;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (Build.VERSION.SDK_INT >= 21) {
Uri[] results = null;
//Check if response is positive
if (resultCode == Activity.RESULT_OK) {
if (requestCode == FCR) {
if (null == mUMA) {
return;
}
if (intent == null) {
//Capture Photo if no image available
if (mCM != null) {
results = new Uri[]{Uri.parse(mCM)};
}
} else {
String dataString = intent.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
}
mUMA.onReceiveValue(results);
mUMA = null;
} else {
if (requestCode == FCR) {
if (null == mUM) return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
mUM.onReceiveValue(result);
mUM = null;
}
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.webview, container, false);
return rootView;
}
#SuppressLint({"SetJavaScriptEnabled", "WrongViewCast"})
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Write your Basic Code
initLayout();
}
private void initLayout() {
handler = new Handler();
webView = (android.webkit.WebView) rootView.findViewById(R.id.webview);
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setSupportMultipleWindows(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.addJavascriptInterface(new AndroidBridge(), "android");
webView.setDrawingCacheEnabled(false);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
// webView.setWebChromeClient(new customWebChromeClient());
webView.setWebChromeClient(new WebChromeClient() {
//For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
getActivity().startActivityForResult(Intent.createChooser(i, "File Chooser"), FCR);
}
// For Android 3.0+, above method not supported in some android 3+ versions, in such case we use this
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
getActivity().startActivityForResult(
Intent.createChooser(i, "File Browser"),
FCR);
}
//For Android 4.1+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
getActivity().startActivityForResult(Intent.createChooser(i, "File Chooser"), FCR);
}
//For Android 5.0+
public boolean onShowFileChooser(
android.webkit.WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
if (mUMA != null) {
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
} catch (IOException ex) {
Log.e(TAG, "Image file creation failed", ex);
}
if (photoFile != null) {
mCM = "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("*/*");
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, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FCR);
return true;
}
#Override
public boolean onCreateWindow(android.webkit.WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
android.webkit.WebView newWebView = new android.webkit.WebView(getActivity());
newWebView.getSettings().setJavaScriptEnabled(true);
newWebView.getSettings().setSupportMultipleWindows(true);
newWebView.getSettings().setLoadWithOverviewMode(true);
newWebView.getSettings().setSupportZoom(false);
newWebView.getSettings().setPluginState(WebSettings.PluginState.ON);
newWebView.getSettings().setBuiltInZoomControls(true);
newWebView.getSettings().setUseWideViewPort(true);
newWebView.getSettings().setAllowFileAccess(true);
newWebView.getSettings().setAllowContentAccess(true);
newWebView.getSettings().setDisplayZoomControls(false);
newWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
newWebView.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
newWebView.setWebChromeClient(new WebChromeClient() {
//For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
getActivity().startActivityForResult(Intent.createChooser(i, "File Chooser"), FCR);
}
// For Android 3.0+, above method not supported in some android 3+ versions, in such case we use this
public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
getActivity().startActivityForResult(
Intent.createChooser(i, "File Browser"),
FCR);
}
//For Android 4.1+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
getActivity().startActivityForResult(Intent.createChooser(i, "File Chooser"), FCR);
}
//For Android 5.0+
public boolean onShowFileChooser(
android.webkit.WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
if (mUMA != null) {
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
} catch (IOException ex) {
Log.e(TAG, "Image file creation failed", ex);
}
if (photoFile != null) {
mCM = "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("*/*");
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, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FCR);
return true;
}
#Override
public void onCloseWindow(android.webkit.WebView window) {
webView.removeAllViews();
webView.removeView(window);
super.onCloseWindow(window);
}
});
newWebView.setWebViewClient(new WebViewClient());
view.addView(newWebView);
android.webkit.WebView.WebViewTransport transport = (android.webkit.WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
return true;
}
#Override
public void onCloseWindow(android.webkit.WebView window) {
webView.removeAllViews();
webView.removeView(window);
super.onCloseWindow(window);
}
});
webView.setWebViewClient(new customWebViewClient());
webView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
try {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimetype);
request.addRequestHeader("User_Agent", userAgent);
request.setDescription("Downloading file");
String fileName = contentDisposition.replace("inline; filename=", "");
fileName = fileName.replace("\"", "");
fileName = fileName.replace("attachment;", "");
fileName = fileName.replace("filename=", "");
fileName = fileName.replace(";", "");
fileName = fileName.replace(" ", "");
request.setTitle(fileName);
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
DownloadManager dm = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getActivity().getApplicationContext(), "파일 다운로드", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
if (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(getActivity(), "첨부파일을 다운 받기 위해\n동의가 필요합니다.", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 110);
} else {
Toast.makeText(getActivity(), "첨부파일을 다운 받기 위해\n동의가 필요합니다.", Toast.LENGTH_SHORT).show();
ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 110);
}
}
}
}
});
webView.getSettings().setBuiltInZoomControls(true);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
webView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
} else {
webView.getSettings().setLoadWithOverviewMode(true);
}
startWebView(url);
}
public void startWebView(String url) {
webView.onResume();
webView.loadUrl(url);
}
// Create an image file
private File createImageFile() throws IOException {
#SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "img_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return File.createTempFile(imageFileName, ".jpg", storageDir);
}
#Override
public void onDestroy() {
super.onDestroy();
}
private class AndroidBridge {
// If Use AndroidBridge. Code Here
}
private class customWebViewClient extends WebViewClient {
#Override
public void onReceivedHttpAuthRequest(android.webkit.WebView view, HttpAuthHandler handler, String host, String realm) {
super.onReceivedHttpAuthRequest(view, handler, host, realm);
}
#Override
public boolean shouldOverrideUrlLoading(android.webkit.WebView view, WebResourceRequest request) {
return true;
}
#Override
public void onPageStarted(android.webkit.WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(android.webkit.WebView view, String url) {
webView.scrollTo(0, 0);
super.onPageFinished(view, url);
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
}

WebView Timeout Issue while accessing an AD authenticated website

I used a timeout boolean value setting 20 seconds after which the timeout should occur and the webview should stop loading the webpage. Here's the code:
Web.java
public class Web extends Activity {
private WebView webView;
final Activity activity = this;
public Uri imageUri;
Global ht;
boolean timeout = true;
ProgressDialog progressDialog;
private static final int FILECHOOSER_RESULTCODE = 2888;
private ValueCallback<Uri> mUploadMessage;
#SuppressWarnings("unused")
private Uri mCapturedImageURI = null;
public static final int REQUEST_SELECT_FILE = 100;
public ValueCallback<Uri[]> uploadMessage;
private ProgressBar progressBar;
Handler myHandler = new Handler(Looper.myLooper());
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_web);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
myHandler = new Handler(Looper.myLooper());
progressBar.setMax(100);
ht = (Global) getApplicationContext();
webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new MyWebViewClient());
final String url = "http://192.168.1.1";
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
//webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
//webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
webView.getSettings().setLoadWithOverviewMode(true);
webView.setFocusable(false);
webView.setFocusableInTouchMode(false);
//webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
if (Build.VERSION.SDK_INT >= 19) {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
} else {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
int DELAY = 1000;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
webView.loadUrl(url);
}
}, DELAY);
/*Timer myTimer = new Timer();
//Start this timer when you create you task
myTimer.schedule(loaderTask, 3000); // 3000 is delay in millies*/
// webView.getSettings().setUseWideViewPort(true);
// Other webview settings
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(true);
webView.setVerticalScrollBarEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setPluginState(PluginState.ON);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setSupportZoom(true);
//webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
// for downloading directly through download manager
final String filename = URLUtil.guessFileName(url,
contentDisposition, mimetype);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, filename);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); //This is important!
intent.addCategory(Intent.CATEGORY_OPENABLE); //CATEGORY.OPENABLE
intent.setType("*/*");//any application,any extension
Toast.makeText(getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded
Toast.LENGTH_LONG).show();
}
});
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
// The undocumented magic method override
// Eclipse will swear at you if you try to put #Override here
// For Android 3.0+
#SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
Web.this.startActivityForResult(
Intent.createChooser(i, "File Chooser"),
FILECHOOSER_RESULTCODE);
}
// For Android 3.0+
#SuppressWarnings({"unused", "rawtypes", "unchecked"})
public void openFileChooser(ValueCallback uploadMsg,
String acceptType) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
Web.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FILECHOOSER_RESULTCODE);
}
// For Android 4.1
#SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType, String capture) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
Web.this.startActivityForResult(
Intent.createChooser(i, "File Chooser"),
Web.FILECHOOSER_RESULTCODE);
}
// For Android 5.0+
#SuppressLint("NewApi")
public boolean onShowFileChooser(WebView mWebView,
ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
if (uploadMessage != null) {
uploadMessage.onReceiveValue(null);
uploadMessage = null;
}
uploadMessage = filePathCallback;
Intent intent = null;
if (Build.VERSION.SDK_INT >= 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;
}
});
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error){
//Your code to do
try {
webView.stopLoading();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(Web.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Could not load content Due to bad connectivity or invalid credentials");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});
alertDialog.show();
}
/*public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
try {
webView.stopLoading();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(Web.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Could not load content Due to bad connectivity or invalid credentials");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
});
alertDialog.show();
super.onReceivedError(webView, errorCode, description, failingUrl);
}
#TargetApi(android.os.Build.VERSION_CODES.M)
#Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
// Redirect to deprecated method, so you can use it in all SDK versions
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
}*/
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
Toast.makeText(getApplicationContext(), "Gathering content, please wait", Toast.LENGTH_SHORT).show();
Runnable run = new Runnable() {
public void run() {
if (timeout) {
// do what you want
try {
webView.stopLoading();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(Web.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Could not load content Due to bad connectivity or invalid credentials");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(Web.this, LoginActivity2.class);
startActivity(i);
finish();
}
});
alertDialog.show();
}
}
};
myHandler.postDelayed(run, 20000);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
progressBar.setProgress(100);
timeout = false;
}
public void onReceivedHttpAuthRequest(WebView view,
HttpAuthHandler handler, String host, String realm) {
handler.proceed("abc", "123");
// To change body of overridden methods use File| Settings| File Templates.
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
} else {
Intent i = new Intent(this, LoginActivity2.class);
startActivity(i);
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage)
return;
Uri result = intent == null || resultCode != RESULT_OK ? null
: intent.getData();
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
/*class loaderTask extends TimerTask {
public void run() {
System.out.println("Times Up");
if(isPageLoadedComplete){
}
}
}*/}
But every time when I try inserting wrong credentials, the boolean value "timeout" gets setted to false instead of giving it true while the page starts loading. I have setted the boolean value to false only when the page is completely loaded(in my onPageFinished()). Finally the page stucks with no result. Any sort of help regarding how to set timeout period if webView fails to load content is helpful for me. I referred these links but had did not worked:
Link1
Link2
Finally got it working with this:
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
if(webView.getProgress()==100)
{
timeout = false;
}
}
Referred from this link:
Android WebView TimeOut

Image Chooser not working for 5.0 and how to upload multiple image

This code is for web view where I am fetching webpage page in that web page there is image choosing activity which upload one image not a multiple image.I wanted to upload multiple image.
So please narrate me what wrong in it and how make work image choose above android version as 5.0+
public class MainActivity extends Activity {
private static final int INPUT_FILE_REQUEST_CODE =1;
private static final int FILECHOOSER_RESULTCODE =2;
private static final String TAG =MainActivity.class.getSimpleName();
private WebView webView;
private WebSettings webSettings;
private ValueCallback<Uri> mUploadMessages;
private Uri mCapturedImageURI=null;
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhoto;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode==FILECHOOSER_RESULTCODE)
{
if (null == this.mUploadMessages) {
return;
}
Uri result=null;
try{
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = intent == null ? mCapturedImageURI : intent.getData();
}
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "activity :"+e,
Toast.LENGTH_LONG).show();
}
mUploadMessages.onReceiveValue(result);
mUploadMessages = null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView=(WebView)findViewById(R.id.webview);
webSettings=webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setAllowFileAccess(true);
webView.setWebViewClient(new WebViewClient());
webView.setWebChromeClient(new WebChromeClient());
if(Build.VERSION.SDK_INT >=19) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}
else if(Build.VERSION.SDK_INT>=11 && Build.VERSION.SDK_INT < 19){
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
webView.loadUrl("http://m.multitechservice.co.in");
}
private File createImageFile() throws Exception{
String timeStamp=new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName= "JPEG_" + timeStamp + "_";
File storageDirectory=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File imageFile=File.createTempFile(imageFileName,".jpg",storageDirectory);
return imageFile;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
#SuppressWarnings("unused")
MenuInflater inflater=getMenuInflater();
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class ChromeClient extends WebChromeClient{
#Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
FileChooserParams fileChooserParams) {
// TODO Auto-generated method stub
if(mFilePathCallback != null){
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback=filePathCallback;
Intent takePictureIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(takePictureIntent.resolveActivity(getPackageManager())!= null){
File photoFile=null;
try{
photoFile=createImageFile();
takePictureIntent.putExtra("Photo_Path", mCameraPhoto);
}catch(Exception ex){
Log.e(TAG, "Unable to create file path",ex);
}
if(photoFile!=null){
mCameraPhoto="file:" +photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
}else{
takePictureIntent=null;
}
}
Intent contentOnSelection=new Intent(Intent.ACTION_GET_CONTENT);
contentOnSelection.addCategory(Intent.CATEGORY_OPENABLE);
contentOnSelection.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, contentOnSelection);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
public void openFileChooser(ValueCallback<Uri> uploadMSG,String acceptType){
mUploadMessages=uploadMSG;
File imageStorage=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"Photo");
if(!imageStorage.exists()){
imageStorage.mkdirs();
}
File file=new File(imageStorage +File.separator +"IMG_" +String.valueOf(System.currentTimeMillis())+".jpg");
mCapturedImageURI=Uri.fromFile(file);
final Intent captureIntent=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent intent=new Intent(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
Intent chooserIntent=Intent.createChooser(intent, "IMAGE CHOOSER");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] {captureIntent});
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
public void openFileChooser(ValueCallback<Uri> uploadMSG){
openFileChooser(uploadMSG," ");
}
public void openFileChooser(ValueCallback<Uri> uploadMsg,String acceptType,String capture){
openFileChooser(uploadMsg,acceptType);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()){
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
public class Client extends WebViewClient {
ProgressDialog progressDialog;
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.contains("mailto:")) {
view.getContext().startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(url)));
return true;
}
else{
view.loadUrl(url);
return true;
}
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if(progressDialog == null){
progressDialog=new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading.........");
progressDialog.show();
}
}
#Override
public void onPageFinished(WebView view, String url) {
try{
if(progressDialog.isShowing()){
progressDialog.dismiss();
progressDialog=null;
}
}catch(Exception e){
e.printStackTrace();
}
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
try{
view.stopLoading();
}catch(Exception ex){
ex.printStackTrace();
}
if(view.canGoBack()){
view.goBack();
}
view.loadUrl("about:blank");
AlertDialog alertDialog=new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Cannot connect to Internet.Please check your internet connection");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if(id == R.id.action_refresh){
webView.reload();
return true;
}
return super.onOptionsItemSelected(item);
}
}

Categories

Resources