Call timeout thread everytime a page load WebView android - android

First time webview loads, thread is called after x seconds, When clicking on a url inside the webview why is the thread not fired again. The thread in pageStart is loading only once, but it needs to fire everytime a url is clicked inside webview.
public class MyAppWebViewClient extends WebViewClient {
public MyAppWebViewClient() {
timeout = true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
showProgressDialog();
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(Constants.DELAYMILIS);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(timeout) {
// do what you want
systemUtils.dismissProgressDialog(activity.getResources().getString(R.string.app_name),activity.getResources().getString(R.string.chargement_message_dialog));
}
}
}).start();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
super.shouldOverrideUrlLoading(view, url);
webContainer.loadUrl(url);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(Constants.DELAYMILIS);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(timeout) {
// do what you want
systemUtils.dismissProgressDialog(activity.getResources().getString(R.string.app_name),activity.getResources().getString(R.string.chargement_message_dialog));
}
}
}).start();
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
timeout = false;
cancelCurrentLoading();
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Log.e("ERROR_LOADING_CODE: ", description);
timeout = false;
noConnection();
}
}
/*
Mehtod to dismiss loading spinner
*/
public static void cancelCurrentLoading() {
showWebView();
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
/*
Method to show and hide webview
*/
public static void showWebView(){
webContainer.setVisibility(View.VISIBLE);
}
public static void hideWebView(){
webContainer.setVisibility(View.GONE);
}

Related

Reduce the time of displaying progress bar in WebView

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();
}
}

Android: TimeOut on WebViewClient

I am trying to implement a TimeOut error handling on a webview. But unfortunately I am doing something wrong, which is causing me huge headaches. Currently I am using a TimerTask. To check the progress of a webpage for 10 seconds. The idea is if the page takes more than 10 seconds to load, the app should display a custom "no I-net" view.
Here is my code so far:
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (mNoInternetConnectionView.getVisibility() == View.VISIBLE) {
mNoInternetConnectionView.setVisibility(View.GONE);
}
mTimer = new Timer();
TimerTask timerTask = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (webView.getProgress() < 100) {
handleInternetProblems();
}
}
});
}
};
mTimer.schedule(timerTask, 10000, 1);
}
#Override
public void onPageFinished(WebView view, String url) {
cancelTimer();
if (!internetError && webView.getVisibility() != View.VISIBLE) {
webView.setVisibility(View.VISIBLE);
}
}
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return mCheckoutUrlHandler.handleUrl(webView, url);
}
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return true;
}
#Override
public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
//handle ssl error
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
handleInternetProblems();
}
});
And here are my handleInternetProblems() and my cancelTimer():
private void handleInternetProblems() {
internetError = true;
webView.setVisibility(View.GONE);
mNoInternetConnectionView.setVisibility(View.VISIBLE);
mKLLoadingAnimation.hide();
cancelTimer();
}
private void cancelTimer() {
if (mTimer != null) {
mTimer.cancel();
mTimer.purge();
mTimer = null;
}
}
The problem is that if I click on an URL on the webview and I try to load another webpage I get mNoInternetConnectionView and I can see that handleInternetProblems() is called multiple times inside TimerTask. What am I doing wrong? How can I prevent this from happening?

Handle loading webclient android

I have problem with web view.
I don't know how to handle loading data( timeout) in web client when I open web success i turn off wifi and continues open web client. it loading forever.(
Here is xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/web_assignment"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<include
android:id="#+id/retry_assignment"
layout="#layout/layout_retry_web"
android:visibility="gone"
/>
<com.lusfold.spinnerloading.SpinnerLoading
android:id="#+id/spinnerLoalding_assignment"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:layout_height="wrap_content"
android:visibility="gone"
/>
<WebView
android:id="#+id/layout_assignment"
android:layout_width="match_parent"
android:layout_height="match_parent"></WebView>
</RelativeLayout>
Code is:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//
tokenManager = new TokenManager(getApplicationContext());
token = tokenManager.GetTokenID();
if (networkStateReceiver.isConnected(this))
checkTimeToken(token);
else {
setVisibleLayout();
}
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onStop() {
super.onStop();
}
private void setVisibleLayout() {
webView.setVisibility(View.GONE);
relativeLayout.setVisibility(View.VISIBLE);
spinnerLoading.setVisibility(View.GONE);
btnRetry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("onclick", "Tap reload");
loadweb();
}
});
}
private void checkTimeToken(final String token) {
//
}
private void loadweb() {
final String strUrl = URL_Utils.Assignments_Load + token;
Log.d("URL_asiagnmentss :", strUrl);
if (networkStateReceiver.isConnectedNetwork(this)) {
webView.loadUrl(strUrl);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
spinnerLoading.setVisibility(View.VISIBLE);
webView.setVisibility(View.INVISIBLE);
spinnerLoading.setPaintMode(1);
spinnerLoading.setCircleRadius(20);
spinnerLoading.setItemCount(8);
Log.d("onPageStarted", "onPageStarted");
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
spinnerLoading.setVisibility(View.INVISIBLE);
webView.setVisibility(View.VISIBLE);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
}
});
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setSupportZoom(true);
webView.setVisibility(View.VISIBLE);
relativeLayout.setVisibility(View.GONE);
} else
setVisibleLayout();
}
Firts of all create one Boolean variable default true which track of whether timeout or not.
After that on your WebViewClient's onPageStarted method you have to put one thread which trigger at your given time.
In the last, onPageFinished set variable false
As shown in the code :-
public class MyWebViewClient extends WebViewClient {
boolean timeout = true;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Runnable run = new Runnable() {
public void run() {
if(timeout) {
// do what you want
showAlert("Connection Timed out", "Whoops! Something went wrong. Please try again later.");
}
}
};
myHandler.postDelayed(run, 5000);
}
public void onPageFinished(WebView view, String url) {
timeout = false;
}
}

Scrolling on webview not working

I have a webview on my 4.1.2 Android, which I load with
public class FullscreenActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
final WebView wv=(WebView)findViewById(R.id.webView1);
String sHTML="Webviewtest";
for(int i=0;i<500;i++){
sHTML=sHTML+"Line " + i + "<br>";
}
wv.loadData(sHTML, "text/html", null);
wv.setScrollY(1500);
wv.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
wv.setScrollY(500);
Toast.makeText(getApplicationContext(), "Done! " + wv.getScrollY(), Toast.LENGTH_SHORT).show();
}
});
}
}
I like the webview to scroll down to a specific postition, but it stays on the top.
any ideas ?
When setScrollY() with a button it works, but I like to set the position after laoding the HTML. I also tried to do it with a Handler, which I call in onPageFinished. This does not work too.
I created a very simple Android project, where everyone can download and test:
https://drive.google.com/folderview?id=0B7yz_IQ1CMblUU03cGd5cEotTVE&usp=sharing
This time it is not android's fault,it has provided us with another approach.
try:
public void onPageFinished(WebView v, String url) {
v.evaluateJavascript("window.scrollTo(0,"+expectedPos/a.getResources().getDisplayMetrics().density+");", null);
super.onPageFinished(v, url);
}
My Solution. I don't like it, but it works. All this mess because of the android framework, that doesn't work like expected...
I added a AsyncTask:
private class Waitforloaded extends AsyncTask<String, Integer, Long> {
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
}
#Override
protected Long doInBackground(String... params) {
// TODO Auto-generated method stub
boolean bgo=true;
int iTries=0;
while(bgo){
iTries=iTries+1;
if(iTries>20 || wv.getContentHeight()>0){
bgo=false;
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
wv.setScrollY(1500);
return null;
}
}
Then calling it in
wv.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Waitforloaded wfl=new Waitforloaded();
wfl.execute("");
}
WebView.setScrollY works for me only when I give it some delay with a timer after the WebView is loaded:
webView.loadData(sHtmlTemplate, "text/html", "utf-8");
Timer t = new Timer(false);
t.schedule(new TimerTask() {
#Override
public void run() {
MainActivity.mainactivity.runOnUiThread(new Runnable() {
public void run() {
webView.setScrollY(500);
}
});
}
}, 300); // 300 ms delay before scrolling

Android WebView TimeOut

Is there a way to set the timeout value in WebView?
I want the WebView to be timeouted if the url is too slow to response.
You can do it by setting up a Timer which checks for progress of current page by calling getProgress() and if it is less than some threshold after some specified time then you can dismiss the loading of the current page.
We can use onLoadResource method of WebViewClient instead of Timer. Like this:
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Log.d("WEBCLIENT", "onPageFinished");
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
Log.d("WEBCLIENT","onLoadResource");
if(webView.getProgress() == 100) {
progressDialog.dismiss();
}
}
}
I use
#Override
public void onReceivedError(WebView view, int errorCod,String description, String failingUrl) {
final Dialog dialog = new Dialog(MainActivity.this, android.R.style.Theme_NoTitleBar_Fullscreen);
dialog.setContentView(R.layout.alert_dialog);
Button btTryAgain = dialog.findViewById(R.id.bt_try_again);
btTryAgain.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
recreate();
}
});
dialog.show();
//Toast with error conection
Toast.makeText(getApplicationContext(), "Your Internet Connection May not be active Or " + description , Toast.LENGTH_LONG).show();
}
Where -alert_dialog- is a layout with a button to retry

Categories

Resources