How to Design "NO INTERNET CONNECTION PAGE" for Android app - android

I want to create a "No internet connection" page when my webapp is not connected to internet and a "retry" button should be there. I Already Created a error.html page and put in asset folder..
#SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity {
//private Button button;
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get webview
webView = (WebView) findViewById(R.id.mywebview);
startWebView("http://abc/ashwini/my.html");
}
private void startWebView(String url) {
//Create new webview Client to show progress dialog
//When opening a url or click on link
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
//Show loader on url load
public void onLoadResource (WebView view, String url) {
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
try{
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
// Javascript inabled on webview
webView.getSettings().setJavaScriptEnabled(true);
// Other webview options
/*
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setBuiltInZoomControls(true);
*/
/*
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);
*/
//Load url in webview
webView.loadUrl(url);
}
// Open previous opened link from history on webview when back button pressed
#Override
// Detect when the back button is pressed
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
}

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get webview
webView = (WebView) findViewById(R.id.mywebview);
if(isConnectionAvailable(getApplicationContext()))
{
startWebView("http://abc/ashwini/nointernet.html");
}
else
{
startWebView("http://abc/ashwini/my.html");
}
}
public static boolean isConnectionAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo netInfo = connectivityManager.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()
&& netInfo.isConnectedOrConnecting()
&& netInfo.isAvailable()) {
return true;
}
}
return false;
}
permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />

this this one :
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
// write your code by which you use to internet
}
else{
final Dialog dialog = new Dialog(your activity name.this);
//setting custom layout to dialog
dialog.setContentView(R.layout.custom_dialog_layout);
dialog.setTitle(" Oops... ");
//adding text dynamically
TextView txt = (TextView) dialog.findViewById(R.id.textView);
txt.setText( "Internet Connection is not Available");
Button dismissButton = (Button) dialog.findViewById(R.id.button);
dismissButton.setText("Retry");
dismissButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
yourActivityname.this.finish();
startActivity(yourActivityname.this.getIntent());
dialog.dismiss();
}
});
dialog.show();
}

Related

How can i block or avoid popup in webview?

the webpage have some popup ads is there any way to prevent the popup from loading when the popup loads the main site doesnt appears is there any way to load the main page with out popups and how can i add a download handler l mean the webview should support downloading .torrent file
public class MainActivity extends AppCompatActivity {
private WebView webView;
private ProgressBar progressBar;
private LinearLayout layoutProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
layoutProgress = (LinearLayout) findViewById(R.id.layoutProgress);
webView.setVisibility(View.GONE);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setBuiltInZoomControls(true);
settings.setSupportZoom(true);
settings.setDisplayZoomControls(false);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
webView.setVisibility(View.VISIBLE);
layoutProgress.setVisibility(View.GONE);
progressBar.setIndeterminate(false);
super.onPageFinished(view, url);
}
public void but(View v){
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
layoutProgress.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
super.onPageStarted(view, url, favicon);
}
});
if(isOnline()) {
webView.loadUrl("http://testsite.com/");
} else {
String summary = "<html><body><font color='red'>No Internet Connection</font></body></html>";
webView.loadData(summary, "text/html", null);
toast("No Internet Connection.");
}
}
private void toast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return (netInfo != null && netInfo.isConnected());
}
public void but(View v){
webView.loadUrl("http://testsite.com/");
}
}
if the url changes then use shouldOverrideUrlLoading with some regex
so
List<String> validUrls = new LinkedList<>();
validUrls.add("https://www\\.google\\.com/*");
validUrls.add("https://www\\.facebook\\.com/*");
#Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (isValidUrl(url)) {
return false;
}
return true;
}
private boolean isValidUrl(String url) {
for (String validUrl : validUrls) {
Pattern pattern = Pattern.compile(validUrl, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(url);
if (matcher.find()) {
return true;
}
}
return false;
}
would match against any www.google.com or facebook.com urls
You can intercept the urls that are opened from the webview, I don't know if it would work with the popup:
WebViewClient client= new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
if (url.equals("popupURL"){
return true;
}
return false;
}
}
webView.setWebViewClient(client);

Android Webview loads images from cache every second time only

Below is my code, I want to load webpage from cache if there's no internet connection, but when there is no connection the page loads without images on the first time and then when I try again its loads, and next time it doesn't load images. Its like its working fine every even time.
public class school extends Fragment {
private WebView webView;
public Main2Activity main2activity;
public static school newInstance() {
return new school();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_school, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
webView = (WebView)
getView().findViewById(R.id.mywebview);
main2activity = (Main2Activity) getActivity();
String url=getResources().getString(R.string.urlSchool);
//String postData = "schoolId="+main2activity.txtschoolId+"&phoneNumber="+main2activity.txtphoneNumber+"&password="+main2activity.txtpassword;
startWebView(url);
}
public void startWebView(final String url) {
int state=0;
ConnectivityManager connMgr = (ConnectivityManager)
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
state=1;
} else {
state=0;
}
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
public void onLoadResource (WebView view, String url) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
progressDialog.dismiss();
}
});
if(state==1) {
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
}
else{
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY);
}
webView.post(new Runnable() {
#Override
public void run() {
webView.loadUrl(url);
}
});
}
}

How to add a progressbar to the android webview

I am trying to add a progress bar in the android webview based app. I have added following code but not working when tested.
Note: index.html have redirect tag which loads random URL. Everything is working fine except the progressbar.
MainActivity.java
public class MainActivity extends ActionBarActivity {
private WebView mWebView;
ProgressBar Pbar;
private final int ID_MENU_EXIT = 1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
Pbar = (ProgressBar) findViewById(R.id.pB1);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.setWebViewClient(new MyAppWebViewClient());
if (isNetworkAvailable())
mWebView.loadUrl("file:///android_asset/www/index.html");
else
mWebView.loadUrl("file:///android_asset/www/404.html");
}
public class myWebClient extends WebViewClient{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Pbar.setVisibility(View.GONE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
//get the MenuItem reference
MenuItem item =
menu.add(Menu.NONE,ID_MENU_EXIT,Menu.NONE,R.string.exitOption);
//set the shortcut
item.setShortcut('5', 'x');
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
//check selected menu item
if(item.getItemId() == ID_MENU_EXIT)
{
//close the Activity
this.finish();
return true;
}
return false;
}
}
Activity_main.xml
<ProgressBar android:id="#+id/pB1"
style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_centerVertical="true"
android:padding="2dip">
</ProgressBar>
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Well,
Use this code for Progress Bar when your WebView waiting for loading WebView. :
Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
Activity:
public class MapActivity extends MenuActivity {
private final static String TAG = "HearingTest";
private WebView webView;
private String urlString;
private ProgressDialog progressDialog;
private Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout);
context = MapActivity.this;
urlString = getString(R.string.location_url);
WebViewSettings();
LoadWebPage(urlString);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Loading...");
progressDialog.setMessage("Please wait.");
//progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
//Do something...
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (progressDialog!=null) {
progressDialog.dismiss();
}
}
};
task.execute((Void[])null);
}
public void LoadWebPage(String url){
try {
webView.loadUrl(url);
Log.d(TAG, "URL" + url + "connected");
}
catch (Exception e) {
Log.d(TAG, "URL: " + url + " couldn't connect.");
}
}
public void WebViewSettings(){
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals(urlString)) {
// This is my web site, so do not override; let my WebView load the page
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;
}
#Override
public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}
});
}
protected void DisplayProgressBar(){
}
}

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");

Check Data Connection before open webView

i am looking for method which will check data connection is enable or disable .
if data enable then open a link in webView else toast (Data is disable).
Below my code which handle webview
public class Question_web extends Activity {
/** Called when the activity is first created. */
WebView webview;
ProgressBar progressBar;
int a;
String value;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.webcontent);
value = getIntent().getExtras().getString("url");
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);
WebView engine = (WebView) findViewById(R.id.webviews);
engine.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent i = new Intent(Intent.ACTION_VIEW);
Toast.makeText(getBaseContext(), "downloading", Toast.LENGTH_SHORT).show();
i.setData(Uri.parse(url));
startActivity(i);
}
});
engine.setWebViewClient(new FixedWebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
progressBar.setVisibility(View.VISIBLE);
}
public void onPageFinished(WebView view, String url)
{
progressBar.setVisibility(View.GONE);
}
});
engine.getSettings().setJavaScriptEnabled(true);
engine.loadUrl(value);
}
public void onBackPressed() {
WebView engine = (WebView) findViewById(R.id.webviews);
String url = engine.getUrl();
if (url.equals(value) ||
url.equals(value)) {
// exit
super.onBackPressed();
} else {
// go back a page, like normal browser
engine.goBack();
}
}
private class FixedWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
We can check to see whether a network connection is available using getActiveNetworkInfo() and isConnected() of NetworkInfo class.
This is example is available on Android doc,
ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// fetch data
} else {
// display error
}
See here and here for details.
Remember to add permissions in manifest. Follow this step by step tutorial.

Categories

Resources