Reduce the time of displaying progress bar in WebView - android

I have problem with reducing the time of displaying progress bar in WebView. For underesting a add image. enter image description here.
Where I can implement some thread of something to stop showing progress bar for one second, while my web running in WebView?
I tried implement thread before showing progress bar in onPageStarted, but it waiting for whole loading page, not only for loading progress bar.
We have very slow loading on web page, so we need showing to users one or two second loading page in webview without progressbar, after this time show "loading" progress bar.
If you have question, please ask me, we need quick respond to resolve this problem. I'm trying to find some solution, but nothing.
Thanks a lot!
There is my ChromeClien.class
public class MyWebChromeClient extends WebChromeClient {
private ProgressListener mListener;
public MyWebChromeClient(ProgressListener listener) {
mListener = listener;
}
#Override
public void onProgressChanged(WebView view, int newProgress) {
mListener.onUpdateProgress(newProgress);
super.onProgressChanged(view, newProgress);
}
public interface ProgressListener {
public void onUpdateProgress(int progressValue);
}}
There is MainActivity.class
public class MainActivity extends AppCompatActivity{
private WebView webview;
ProgressDialog prDialog;
String cekani;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CookieManager.getInstance().setAcceptCookie(true);
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
if (isFirstRun) {
//show start activity
startActivity(new Intent(MainActivity.this, PrvniSpusteni.class));
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
if(KontrolaInternetu.isInternetAvailable(MainActivity.this)) //Vrátí hodnotu TRUE, pokud je připojení k internetu k dispozici
{
webview =(WebView)findViewById(R.id.webView);
//Nastavení webové stránky
webview.loadUrl(getString(R.string.url_aplikace));
webview.setWebViewClient(new MyWebViewClient());
//Puštění JavaScriptu pro web
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setUseWideViewPort(true);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
WebSettings ws = webview.getSettings();
ws.setJavaScriptEnabled(true);
ws.setAllowFileAccess(true);
if (android.os.Build.VERSION.SDK_INT >= 21) {
CookieManager.getInstance().setAcceptThirdPartyCookies(webview, true);
}else {
CookieManager.getInstance().setAcceptCookie(true);
}
webview.setWebChromeClient(new WebChromeClient(){
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public void onPermissionRequest(final PermissionRequest request) {
request.grant(request.getResources());
}
});
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.ECLAIR) {
try {
Log.d(TAG, "Enabling HTML5-Features");
Method m1 = WebSettings.class.getMethod("setDomStorageEnabled", new Class[]{Boolean.TYPE});
m1.invoke(ws, Boolean.TRUE);
Method m2 = WebSettings.class.getMethod("setDatabaseEnabled", new Class[]{Boolean.TYPE});
m2.invoke(ws, Boolean.TRUE);
Method m3 = WebSettings.class.getMethod("setDatabasePath", new Class[]{String.class});
m3.invoke(ws, "/data/data/" + getPackageName() + "/databases/");
Method m4 = WebSettings.class.getMethod("setAppCacheMaxSize", new Class[]{Long.TYPE});
m4.invoke(ws, 1024*1024*8);
Method m5 = WebSettings.class.getMethod("setAppCachePath", new Class[]{String.class});
m5.invoke(ws, "/data/data/" + getPackageName() + "/cache/");
Method m6 = WebSettings.class.getMethod("setAppCacheEnabled", new Class[]{Boolean.TYPE});
m6.invoke(ws, Boolean.TRUE);
Log.d(TAG, "Enabled HTML5-Features");
}
catch (NoSuchMethodException e) {
Log.e(TAG, "Reflection fail", e);
}
catch (InvocationTargetException e) {
Log.e(TAG, "Reflection fail", e);
}
catch (IllegalAccessException e) {
Log.e(TAG, "Reflection fail", e);
}
}
}
else
{
//Zobrazení AlertDialogu pokud není připojení k internetu
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!isFinishing()){
new AlertDialog.Builder(MainActivity.this)
.setTitle(getString(R.string.no_internet))
.setMessage(getString(R.string.internet))
.setCancelable(false)
.setIcon(R.drawable.icon)
.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
System.exit(0);
}})
.setNegativeButton(getString(R.string.zrusit), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}})
.show();
}
}
});
}
}
//Při stisknutí tlačítka zpět se uživatel vrátí ve webview nazpět bez toho, aby aplikace spadla.
private final String TAG = MainActivity.class.getSimpleName();
// Progress bar - zobrazí se tehdy, pokud čekám na načítání stránky
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
prDialog = new ProgressDialog(MainActivity.this);
prDialog.setIcon(R.drawable.icon);
prDialog.setMessage(getString(R.string.nacitani_webove_stranky));
prDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(prDialog!=null){
prDialog.dismiss();
}
}
}
//Při stisknutí tlačítka zpět se uživatel dostane zpět pouze ve webview
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack() == true){
webview.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.endsWith(".mp3")) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "audio/*");
view.getContext().startActivity(intent);
return true;
} else if (url.endsWith(".mp4") || url.endsWith(".3gp")) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "video/*");
view.getContext().startActivity(intent);
return true;
} else {
return true;
}}}

Hey bro, you don't necessarily need to implement threads for your
requirement. Firstly you can load the url in the webview and after a
particular time period you can start displaying progress bar. For
calling the progress bar after certain time period you can use
Handler.
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 100ms
prDialog = new ProgressDialog(MainActivity.this);
prDialog.setIcon(R.drawable.icon);
prDialog.setMessage(getString(R.string.nacitani_webove_stranky));
prDialog.show();
}
}, 100);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(prDialog!=null){
prDialog.dismiss();
}
}

Related

WebView is not loading webpage

I am using WebView for loading a website. But it is very slow and is leaking when specific websites are loaded.
I am loading WebView with the following code.
#Override
protected void onNewIntent(Intent intent) {
if (intent.getStringExtra("url") != null) {
webView.loadurl(intent.getStringExtra("url"));
}
}
But I am calling webView.loadUrl(Config.URL); (Config.URL may contain same url as specified above) in onCreate() method after initializing WebView with the following.
this.webView = (WebView) findViewById(R.id.wv);
this.webView.getSettings().setJavaScriptEnabled(true);
this.webView.getSettings().setLoadsImagesAutomatically(true);
this.webView.getSettings().setDomStorageEnabled(true);
this.webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
MyClient client = new MyClient(WebActivity.this, (ProgressBar)findViewById(R.id.progressBar));
webView.setWebViewClient(client);
Loading a from onCreate() is working fine (not fine, it's too slow). But
the same URL that is loading from onNewIntent() is not working!!!.
After I did this inonNewIntent() no URLs got loaded using
webView.loadurl() and the current page is getting immovable. ie. the
scrollbars are moving in WebView but page is not scrolling. I tested
the same URL in onCreate() and it is working.
For doing that I am passing url with
intent.putExtra("url", Config.URL+targetUrl);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
with the pending intent from the notifications. Although it is working in some devices i.e Google Nexus. But it is not working on most of the phones.
I have
android:hardwareAccelerated="true"
Myclient
public class MyClient extends WebViewClient{
private Context context;
private Activity activity;
private Handler handler;
private Runnable runnable;
private ProgressBar viewBar;
private String ret,ret2;
public void setFirstLoad(boolean firstLoad) {
this.firstLoad = firstLoad;
}
private boolean firstLoad=false;
public MyClient(Activity activity, ProgressBar bar) {
this.context = activity.getApplicationContext();
this.activity = activity;
viewBar=bar;
handler=new Handler();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
/*if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL,
Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}else if(url.startsWith("http:") || url.startsWith("https:")) {
*//*view.setVisibility(View.GONE);
viewBar.setVisibility(View.VISIBLE);*//*
view.loadUrl(url);
}
return true;*/
if (Uri.parse(url).getHost().equals("www.somepage.com")) {
return false;
}
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
try {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
Answers.getInstance().logShare(new ShareEvent()
.putContentId(Build.USER)
.putMethod(shareName(url))
.putContentName(contentDecode(url))
.putContentType("news_share"));
}catch (android.content.ActivityNotFoundException e){
Log.e("Activity not found",e.toString());
Toast.makeText(context,"Application not found",Toast.LENGTH_LONG).show();
}
return true;
}
#Override
public void onReceivedError(final WebView view, int errorCode, String description, final String failingUrl) {
//Clearing the WebView
try {
view.stopLoading();
} catch (Exception e) {
}
try {
view.clearView();
} catch (Exception e) {
}
if (view.canGoBack()) {
view.goBack();
}
view.loadUrl("about:blank");
//Showing and creating an alet dialog
AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity);
alertDialog.setTitle("Error");
alertDialog.setMessage("No internet connection was found!");
alertDialog.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
view.loadUrl(failingUrl);
}
});
AlertDialog alert = alertDialog.create();
alert.show();
//Don't forget to call supper!
super.onReceivedError(view, errorCode, description, failingUrl);
}
#Override
public void onLoadResource(final WebView view, String url) {
super.onLoadResource(view, url);
//injectScriptFile(view, "js/script.js");
injectCSS(view,"css/style.css");
if (firstLoad){
firstLoad=false;
view.setVisibility(View.INVISIBLE);
viewBar.setVisibility(View.VISIBLE);
runnable=new Runnable() {
#Override
public void run() {
viewBar.setVisibility(View.GONE);
view.setVisibility(View.VISIBLE);
}
};
handler.postDelayed(runnable,2000);
}
// test if the script was loaded
// view.loadUrl("javascript:setTimeout(hideMe(), 200)");
}
/*#Override
public void onPageFinished(final WebView view, String url) {
//System.gc();
}*/
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
System.gc();
}
The question is: What is the problem when using loadurl() method in onNewIntent()?
Try this from where you loads webview
web.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
});
You can use the webclient to handle the webview. Here I include the javascript with loading.
String aboutURL="YOUR URL";
final ProgressDialog pd = ProgressDialog.show(, "", "Please wait", true);
WebSettings settings=Webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAppCacheEnabled(true);
settings.setDomStorageEnabled(true);
settings.setLoadsImagesAutomatically(true);
settings.setDatabaseEnabled(true);
settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
Webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
pd.show();
}
#Override
public void onPageFinished(WebView view, String url) {
pd.dismiss();
}
});
Webview.loadUrl(aboutURL);
Here Loading is processed based on network
Use Handler to post a delay action as below will fix this, but I don't known why.
new Handler().post(webView.loadurl(url));

How to Handle WebView in Android 4.2 and 4.1

My Webview works in android 4.4.4 and higher.How can I handle it in all android devices?!
I mean I tried many ways to show PaymentGateWay in Webview but it`s just shown url address in webview page(Cant Load Url).how can I do it with this code?
WebSettings webSetting = wv.getSettings();
webSetting.setJavaScriptEnabled(true);
webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
final JavaScriptInterface JavaScriptInterface = new JavaScriptInterface(WebViewPaymentByBankActivity.this);
wv.addJavascriptInterface(JavaScriptInterface, "Android");
//webView.setWebChromeClient(new MyWebChromeClient());
//webView.getSettings().setSupportMultipleWindows(true);
//webSetting.setPluginState(WebSettings.PluginState.ON);
//webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
//webSetting.setDomStorageEnabled(true);
webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSetting.setAppCacheEnabled(true);
wv.setWebChromeClient(new WebChromeClient() {
public boolean onJsAlert(WebView view, String url, String message, final android.webkit.JsResult result) {
//Toast.makeText(WebViewPaymentByBankActivity.this, message, Toast.LENGTH_LONG).show();
result.confirm();
return true;
}
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 1000);
if (progress == 100) {
}
}
});
wv.setWebViewClient(new WebViewClient() {
#JavascriptInterface
#Override
public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
if (!loadingFinished) {
redirect = true;
}
loadingFinished = false;
wv.loadUrl(urlNewString);
url_result = urlNewString;
uri = Uri.parse(url_result);
String[] result = url_result.split("://");
protocol = result[0];
host = result[1];
if (protocol.equals("inapp")) {
if (host.equals("Error")) {
Intent intent = new Intent(WebViewPaymentByBankActivity.this,PaymentActivity.class);
startActivity(intent);
WebViewPaymentByBankActivity.this.finish();
}
else if (host.equals("Success")) {
Constants.ck_pay=true;
BasketFragment.sum = 0;
BasketFragment.txt_view_badge.setText("");
BasketFragment.txt_view_badge.setVisibility(View.GONE);
PaymentActivity.txt_view_pay_total.setText("0");
PaymentActivity.txt_view_pay_payable.setText("0");
WebViewPaymentByBankActivity.this.finish();
}
}
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
if (!redirect) {
loadingFinished = true;
}
if (loadingFinished && !redirect) {
//HIDE LOADING IT HAS FINISHED
} else {
redirect = false;
}
super.onPageFinished(view, url);
view.clearCache(true);
}
#Override
#JavascriptInterface
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
super.onReceivedSslError(view, handler, error);
handler.proceed();
}
});
}
public class JavaScriptInterface {
Context mContext;
/**
* Instantiate the interface and set the context
*/
JavaScriptInterface(Context c) {
mContext = c;
}
/**
* Show a toast from the web page
*/
#JavascriptInterface
public void paymentResponse(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
#Override
#JavascriptInterface
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
wv.goBack();
Intent intent = new Intent(WebViewPaymentByBankActivity.this, PaymentActivity.class);
startActivity(intent);
WebViewPaymentByBankActivity.this.finish();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
Intent intent = new Intent(WebViewPaymentByBankActivity.this, PaymentActivity.class);
startActivity(intent);
WebViewPaymentByBankActivity.this.finish();
return super.onKeyDown(keyCode, event);
}

Google sign in not working android webview app

I've created Android App with the webview. When trying to sign in with Google, it first asks for username & password, then the screen with the message 'Please close this window' shows up & nothing happens.
Also, the user is not logged in.
P.S. This works absolutely fine with my mobile website which itself is ported to Android Webview App. Can anyone tell why that doesn't work? I'm completely new to Android.
Two things in webview create problems in google sign-in.
Google doesn't allow us to sign-in from webview nowadays. So, User-Agent needs to be customized.
Popup handling in webview isn't appropriate. So, a function override is needed.
Using custom User-Agent and an AlertDialog in WebChromeClient to handle popups solve the issues for me.
Here's the full code:
public class MainActivity extends AppCompatActivity {
private Context contextPop;
private WebView webViewPop;
private AlertDialog builder;
private String url = "https://example.com";
private WebView webView;
private String userAgent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// to continue loading a given URL in the current WebView.
// needed to handle redirects.
return false;
}
});
webView.loadUrl(url);
WebSettings webSettings = webView.getSettings();
// Set User Agent
//userAgent = System.getProperty("http.agent");
// the upper line sometimes causes "403: disallowed user agent error"
userAgent = "";
webSettings.setUserAgentString(userAgent + "Your App Info/Version");
// Enable Cookies
CookieManager.getInstance().setAcceptCookie(true);
if(android.os.Build.VERSION.SDK_INT >= 21)
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
// WebView Tweaks
webSettings.setJavaScriptEnabled(true);
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
webSettings.setAppCacheEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
// Handle Popups
webView.setWebChromeClient(new CustomChromeClient());
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
contextPop = this.getApplicationContext();
}
#Override
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
}
else {
//super.onBackPressed();
// Terminate the app
finishAffinity();
System.exit(0);
}
}
class CustomChromeClient extends WebChromeClient {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
webViewPop = new WebView(contextPop);
webViewPop.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// to continue loading a given URL in the current WebView.
// needed to handle redirects.
return false;
}
});
// Enable Cookies
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
if(android.os.Build.VERSION.SDK_INT >= 21) {
cookieManager.setAcceptThirdPartyCookies(webViewPop, true);
cookieManager.setAcceptThirdPartyCookies(webView, true);
}
WebSettings popSettings = webViewPop.getSettings();
// WebView tweaks for popups
webViewPop.setVerticalScrollBarEnabled(false);
webViewPop.setHorizontalScrollBarEnabled(false);
popSettings.setJavaScriptEnabled(true);
popSettings.setSaveFormData(true);
popSettings.setEnableSmoothTransition(true);
// Set User Agent
popSettings.setUserAgentString(userAgent + "Your App Info/Version");
// to support content re-layout for redirects
popSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
// handle new popups
webViewPop.setWebChromeClient(new CustomChromeClient());
// set the WebView as the AlertDialog.Builder’s view
builder = new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT).create();
builder.setTitle("");
builder.setView(webViewPop);
builder.setButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
webViewPop.destroy();
dialog.dismiss();
}
});
builder.show();
builder.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(webViewPop);
resultMsg.sendToTarget();
return true;
}
#Override
public void onCloseWindow(WebView window) {
//Toast.makeText(contextPop,"onCloseWindow called",Toast.LENGTH_SHORT).show();
try {
webViewPop.destroy();
} catch (Exception e) {
Log.d("Webview Destroy Error: ", e.getStackTrace().toString());
}
try {
builder.dismiss();
} catch (Exception e) {
Log.d("Builder Dismiss Error: ", e.getStackTrace().toString());
}
}
}
}
Here is the working code:
public class MainActivity extends Activity {
protected WebView mainWebView;
// private ProgressBar mProgress;
private Context mContext;
private WebView mWebviewPop;
private FrameLayout mContainer;
private ProgressBar progress;
private String url = "http://m.example.com";
private String target_url_prefix = "m.example.com";
public void onBackPressed() {
if (mainWebView.isFocused() && mainWebView.canGoBack()) {
mainWebView.goBack();
} else {
super.onBackPressed();
finish();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this.getApplicationContext();
// Get main webview
mainWebView = (WebView) findViewById(R.id.webView);
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mainWebView.setWebContentsDebuggingEnabled(true);
}
mainWebView.getSettings().setUserAgentString("example_android_app");
// Cookie manager for the webview
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
// Get outer container
mContainer = (FrameLayout) findViewById(R.id.webview_frame);
if (!InternetConnection.checkNetworkConnection(this)) {
showAlert(this, "No network found",
"Please check your internet settings.");
} else {
// Settings
WebSettings webSettings = mainWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
mainWebView.setWebViewClient(new MyCustomWebViewClient());
mainWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
mainWebView.setWebChromeClient(new MyCustomChromeClient());
mainWebView.loadUrl(url);
}
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.example_main, menu);
// return true;
// }
private class MyCustomWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progress.setProgress(0);
progress.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String host = Uri.parse(url).getHost();
Log.d("shouldOverrideUrlLoading", host);
//Toast.makeText(MainActivity.this, host,
//Toast.LENGTH_SHORT).show();
if (host.equals(target_url_prefix)) {
// This is my web site, so do not override; let my WebView load
// the page
if (mWebviewPop != null) {
mWebviewPop.setVisibility(View.GONE);
mContainer.removeView(mWebviewPop);
mWebviewPop = null;
}
return false;
}
if (host.contains("m.facebook.com") || host.contains("facebook.co")
|| host.contains("google.co")
|| host.contains("www.facebook.com")
|| host.contains(".google.com")
|| host.contains(".google.co")
|| host.contains("accounts.google.com")
|| host.contains("accounts.google.co.in")
|| host.contains("www.accounts.google.com")
|| host.contains("www.twitter.com")
|| host.contains("secure.payu.in")
|| host.contains("https://secure.payu.in")
|| host.contains("oauth.googleusercontent.com")
|| host.contains("content.googleapis.com")
|| host.contains("ssl.gstatic.com")) {
return false;
}
// Otherwise, the link is not for a page on my site, so launch
// another Activity that handles URLs
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//startActivity(intent);
//return true;
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
progress.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
Log.d("onReceivedSslError", "onReceivedSslError");
// super.onReceivedSslError(view, handler, error);
}
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
public void showAlert(Context context, String title, String text) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle(title);
// set dialog message
alertDialogBuilder.setMessage(text).setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
finish();
}
}).create().show();
}
private class MyCustomChromeClient extends WebChromeClient {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
mWebviewPop = new WebView(mContext);
mWebviewPop.setVerticalScrollBarEnabled(false);
mWebviewPop.setHorizontalScrollBarEnabled(false);
mWebviewPop.setWebViewClient(new MyCustomWebViewClient());
mWebviewPop.getSettings().setJavaScriptEnabled(true);
mWebviewPop.getSettings().setSavePassword(false);
mWebviewPop.setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
mContainer.addView(mWebviewPop);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(mWebviewPop);
resultMsg.sendToTarget();
return true;
}
#Override
public void onProgressChanged(WebView view, int newProgress) {
// TODO Auto-generated method stub
super.onProgressChanged(view, newProgress);
MainActivity.this.setValue(newProgress);
}
#Override
public void onCloseWindow(WebView window) {
Log.d("onCloseWindow", "called");
}
}
}
mainWebView.getSettings().setUserAgentString("example_android_app");
fixed it for me
just changed mainWebView to what my webview was called. In my case, i set it to
webView.getSettings().setUserAgentString("example_android_app");

How to load the data in webview page by page in android

I am using webview to display the html data.It is working fine if the data is less(less than 1 mb)..I am using following code
mDecryptDataWv.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
DebugLog.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
//showProgressDialog();
DebugLog.i(TAG, "************onPageStarted **************");
}
#Override
public void onPageFinished(WebView view, String url) {
DebugLog.i(TAG, "************onPageFinished **************");
if (mProgressDialog != null) {
if (mProgressDialog.isShowing()) {
DebugLog.i(TAG, "mProgressDialog ::::::stopping");
mProgressDialog.dismiss();
mProgressDialog = null;
}
}
If the data is more then 1MB it is taking more time to complete the loading.so my intention is to load the data page by page upon user scrolling with progress dialog..Can anyone has idea?
// I used this class and my code is working fime at my side please try this may be it will help you
public class WebViewActivity extends Activity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
private TextView header_maintext;
private TextView headeroptiontext;
private RelativeLayout back;
private String url_string="http://www.google.com";
private String header_maintext_string="Your text";
/** Called when the activity is first created. */
#SuppressLint("SetJavaScriptEnabled") #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.webview_layout);
webview = (WebView)findViewById(R.id.webview01);
header_maintext= (TextView)findViewById(R.id.header_maintext);
header_maintext.setText(header_maintext_string);
headeroptiontext = (TextView)findViewById(R.id.headeroptiontext);
headeroptiontext.setVisibility(View.GONE);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
back = (RelativeLayout) findViewById(R.id.back_layout);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(webview.canGoBack() == true)
{
webview.goBack();
}
else
{
finish();
}
}
});
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(WebViewActivity.this, "My application", "Loading...");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(WebViewActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
webview.loadUrl(url_string);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack() == true){
webview.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}

To implement horizontal progressbar

I am Trying to implement the horizontal progressbar.But I am not understanding how to implement it in my class.Now I have implemented the dialog box which is in the format of sphener,But I want it in horizontal format showing progress of activity I am downloading some contents at that time it should show the progress.
My code is
public class Loginwebview extends Activity {
WebView webview;
String url1;
Bundle bundle=null;
private ProgressDialog progressDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.weblogin);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
bundle = new Bundle();
webview.setWebViewClient(new WebViewClient()
{
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
url1=url.toString();
bundle.putString("parameter", url1);
progressDialog = ProgressDialog.show(Loginwebview.this, "", "Loading...");
new Thread() {
public void run() {
try{
if(url1.contains("&mydownloads=true"))
{
if(url1.contains(".zip"))
{
sleep(150000);
Intent i1 = new Intent(Loginwebview.this, DownloadZipActivity.class);
i1.putExtras(bundle);
startActivityForResult(i1,0);
}
else
{
sleep(40000);
Intent i2 = new Intent(Loginwebview.this, DownloadOther.class);
i2.putExtras(bundle);
startActivityForResult(i2, 0);
}
}
else if(url1.contains("mydownloads=true"))
{
Log.d("its in Mydownloadssss",url1.toString());
Intent i3=new Intent(Loginwebview.this,Downloadlist.class);
i3.putExtras(bundle);
startActivityForResult(i3, 0);
}
}
catch(Exception e)
{
}
progressDialog.dismiss();
}
}.start();
return true;
}
public void onPageFinished(WebView view, String url1) {
Log.i("inside onpage", "Finished loading URL: " +url1);
String mainurl=url1;
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e("onReceivedError", "Error: " + description);
}
});
webview.loadUrl("http://xxx/PublicModules/UserLoginVerify.aspx?userid=809&deviceid=DA0CE50D-0EEB-5E8E-9DCA-AED00F9BDFE5");
}
}

Categories

Resources