How can i block or avoid popup in webview? - android

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

Related

Android How to make full screen Video?

When I make a video full screen in WebView, the toolbar is not hidden. How can I hide it? Below you can see the codes I use.I'm using fragment and the navigation drawer menu.
When I make a video full screen in WebView, the toolbar is not hidden. How can I hide it? Below you can see the codes I use.I'm using fragment and the navigation drawer menu.
Full screen
public class searchWebFragment extends Fragment {
public searchWebFragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.searchwb, container, false);
final ProgressBar progressBar = (ProgressBar) v.findViewById(R.id.progressBarHome);
final WebView webView = (WebView) v.findViewById(R.id.wv_home);
final EditText araTxt = (EditText)v.findViewById(R.id.araTxt);
final Button araBtn = (Button)v.findViewById(R.id.araBtn);
final TextView uyariTxt = (TextView)v.findViewById(R.id.uyariTxt);
progressBar.setVisibility(View.INVISIBLE);
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView webView, int i, String s, String d1) {
webView.loadUrl("file:///android_asset/error.html");
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.INVISIBLE);
}
});
webView.getSettings().setBuiltInZoomControls(true);
webView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, url);
DownloadManager dm = (DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getActivity().getApplicationContext(), "Dosya İndiriliyor", //To notify the Client that the file is being downloaded
Toast.LENGTH_LONG).show();
}
});
webView.setVisibility(View.INVISIBLE);
araBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
webView.setVisibility(View.VISIBLE);
String aranacaksey = araTxt.getText().toString();
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setAppCacheEnabled(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
String url = "http://www.ifsalar.16mb.com/?s=" + aranacaksey;
webView.loadUrl(url);
araTxt.setVisibility(View.INVISIBLE);
araBtn.setVisibility(View.INVISIBLE);
uyariTxt.setVisibility(View.INVISIBLE);
}
});
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (webView.canGoBack()) {
webView.goBack();
}
return true;
}
return false;
}
});
return v;
}
}
I would recommend you to try out the follow code and remove the listeners which are related to loading the contents of your WebView.
You need to implement the method to load the website in your webview first.
private void loadWebsite() {
ConnectivityManager connectivityManager = (ConnectivityManager) getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager .getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
mWebView.loadUrl("yourURL");
} else {
mWebView.setVisibility(View.GONE);
}
}
From here, you need to implement 2 different class "Browser_Home" and "MyChrome". For testing purposes, just write it outside searchWebFragment and later on you can implement it as a separate java file. With only the Browser_Home class, the fullscreen button will be disabled. When MyChrome class is added, fullscreen button is enabled and toolbar should disappear as intended.
class Browser_home extends WebViewClient {
Browser_home() {
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
setTitle(view.getTitle());
progressBar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}
private class MyChrome extends WebChromeClient {
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
protected FrameLayout mFullscreenContainer;
private int mOriginalOrientation;
private int mOriginalSystemUiVisibility;
MyChrome() {}
public Bitmap getDefaultVideoPoster()
{
if (mCustomView == null) {
return null;
}
return BitmapFactory.decodeResource(getApplicationContext().getResources(), 2130837573);
}
public void onHideCustomView()
{
((FrameLayout)getWindow().getDecorView()).removeView(this.mCustomView);
this.mCustomView = null;
getWindow().getDecorView().setSystemUiVisibility(this.mOriginalSystemUiVisibility);
setRequestedOrientation(this.mOriginalOrientation);
this.mCustomViewCallback.onCustomViewHidden();
this.mCustomViewCallback = null;
}
public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback)
{
if (this.mCustomView != null)
{
onHideCustomView();
return;
}
this.mCustomView = paramView;
this.mOriginalSystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();
this.mOriginalOrientation = getRequestedOrientation();
this.mCustomViewCallback = paramCustomViewCallback;
((FrameLayout)getWindow().getDecorView()).addView(this.mCustomView, new FrameLayout.LayoutParams(-1, -1));
getWindow().getDecorView().setSystemUiVisibility(3846);
}
}
And finally, apply the following functions and attributes to your webview and give it another try. Remember to apply these within your OnCreate method:
mWebView.setWebViewClient(new Browser_home());
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
loadWebsite();
Let me know if this works and I can credit the corresponding person for the assistance with the code and classes.
create a folder row and copy the video on raw folder on resources and do the following steps,
On your XML file add VideoView,
<VideoView
android:id="#+id/vdoPlayer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"/>
On your .java class file do,
Uri uri = Uri.parse("android.resource://Your package name Here/" + R.raw.welcome_video);
vdoPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
vdoPlayer.setVideoURI(uri);
vdoPlayer.start();

Can't load url with android WebView

I am loading some urls in my app using android WebView and all successful. But when i am trying to load this url:
http://dev.infibond.com/cloud/instagram?user_profile=https%3A%2F%2Fscontent.cdninstagram.com%2Ft51.2885-19%2Fs150x150%2F13534190_829691380497090_1099495058_a.jpg&user_name=infibondtest
But for some reason i am failing - "view.loadUrl(url);" in "shouldOverrideUrlLoading" doesn't show the page and doesn't load another url. just shows a white page.
The response code from the server is 304.
Before i am getting to this url, i am doing authentication with Instagram and sending the access token as a cookie.
public class CloudWebViewActivity extends ActivityBase {
public static final String TAG = "WebViewActivity";
private static final String WEB_VIEW_TOKEN = "token";
private static final String WEB_VIEW_TITLE = "title";
private static final String WEB_VIEW_URL = "url";
private ProgressBar mPbProgress;
private Toolbar mToolbar;
private String mTitle, mUrl;
public static void setInstance(Context context, String title, String url) {
Intent starter = new Intent(context, CloudWebViewActivity.class);
starter.putExtra(WEB_VIEW_TITLE, title);
starter.putExtra(WEB_VIEW_URL, url);
context.startActivity(starter);
}
// MARK: Lifecycle
protected void onCreate(Bundle savedInstanceState) {
mTitle = getIntent().getStringExtra(WEB_VIEW_TITLE);
mUrl = getIntent().getStringExtra(WEB_VIEW_URL);
super.onCreate(savedInstanceState);
AppInstance.sharedInstance().getBus().register(this);
}
#Override
protected void onResume() {
super.onResume();
AppInstance.sharedInstance().setSelf();
mToolbar.setTitle(mTitle);
mPbProgress.setVisibility(View.VISIBLE);
}
#Override
protected void onDestroy() {
super.onDestroy();
AppInstance.sharedInstance().getBus().unregister(this);
}
#SuppressLint("SetJavaScriptEnabled")
public void findViews() {
setContentView(R.layout.webview_activity);
mPbProgress = (ProgressBar) findViewById(R.id.pBProgress);
final WebView mWebView = (WebView) findViewById(R.id.webView);
if (mWebView != null) {
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.setWebViewClient(webViewClient);
// Register a new JavaScript interface called HTMLOUT
mWebView.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
}
if (JavaUtils.isNotNullNotEmptyNotWhiteSpaceOnly(mUrl) && mWebView != null) {
String cookieString = WEB_VIEW_TOKEN + "=" + NetworkManager.instance().getToken();
CookieManager.getInstance().setCookie(mUrl, cookieString);
mWebView.loadUrl(mUrl);
} else {
InfiLogger.getInstance().logRemoteException(new RuntimeException("Cloud service: " + mTitle + " came with an empty/null url address"));
AndroidUtils.showToast(R.string.error_cant_load_url);
}
}
#Override
public Toolbar setToolbar() {
mToolbar = (Toolbar) findViewById(R.id.mToolbar);
if (mToolbar != null) {
mToolbar.setVisibility(View.VISIBLE);
}
return mToolbar;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
private void handleProgressBarVisibility(String url) {
if (url.contains("login") ||
url.contains("https://api.twitter.com/oauth/authorize?oauth_token=") ||
url.contains("https://vimeo.com/log_in") ||
url.contains(".jpg")) {
mPbProgress.setVisibility(View.GONE);
} else {
mPbProgress.setVisibility(View.VISIBLE);
}
}
private final WebViewClient webViewClient = new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
handleProgressBarVisibility(url);
String cookieString = WEB_VIEW_TOKEN + "=" + NetworkManager.instance().getToken();
CookieManager.getInstance().setCookie(mUrl, cookieString);
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, final String url) {
if (url.startsWith("http://dev.infibond.com/api/cloud/")) {
mPbProgress.setVisibility(View.GONE);
// This call inject JavaScript into the page which just finished loading.
view.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
AndroidUtils.showToast(error.getDescription());
} else {
AndroidUtils.showToast(R.string.gen_Something_went_wrong);
}
mPbProgress.setVisibility(View.INVISIBLE);
}
};
// An instance of this class will be registered as a JavaScript interface
class MyJavaScriptInterface {
#JavascriptInterface
#SuppressWarnings("unused")
public void processHTML(String html) {
// process the html as needed by the app
InfiLogger.d("infi", "html: " + html);
if (html.contains("code")) {
final boolean success;
if (html.contains("\"code\":200")) {
AndroidUtils.showToast(AndroidUtils.getString(R.string.cloud_sync_start) + mTitle);
success = true;
} else {
AndroidUtils.showToast(AndroidUtils.getString(R.string.gen_Something_went_wrong));
success = false;
}
AppInstance.sharedInstance().getBus().post(new CloudConnectionStateChangedBusEvent(mTitle, success));
finish();
}
}
}
}
I am not 100% sure, but it seems like you have a lot of small errors. I think the one in question is here:
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
handleProgressBarVisibility(url);
String cookieString = WEB_VIEW_TOKEN + "=" +
NetworkManager.instance().getToken();
CookieManager.getInstance().setCookie(mUrl, cookieString);
view.loadUrl(url);
return true;
}
The view.loadUrl(url) seems very wrong to me. I think you may need to change this to something like:
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("dev.infibond.com")) {
return false;
}
// otherwise, they are leaving the site, so open a new
// browser instead
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
And remove the guts of what you did here. Most of it is findViews() and should not be repeated anyway. I'm guessing this is what you meant to do with
handleProgressBarVisibility(url) in the WebViewClient but I'm not really sure:
#Override
public void onLoadResource(WebView view, String url) {
handleProgressBarVisibility(url);
}

Android : Progressbar to load url, continues to load

In my application, i'm using a webview to open a url. The url is very simple, it just takes secs to load. But the progress bar doesn't hide when the url loads completely. I'm not able to figure out whats wrong. please help me. Below i'm posting the code.
WebView Class
public class noti_cse extends BaseActivity {
private WebView webView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.noti_cse);
// overridePendingTransition(0, 0);
// webView = (WebView) findViewById(R.id.webcse);
// webView.setWebViewClient(new MyWebViewClient());
if (!DetectConnection.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
} else {
webView = (WebView) findViewById(R.id.webcse);
webView.setWebViewClient(new CustomWebViewClient());
webView.clearCache(true);
webView.clearHistory();
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setBuiltInZoomControls(true);
startWebView("http://notify.php");
}
// webView.getSettings().setJavaScriptEnabled(true);
// startWebView("http://notify.php");
// webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
// webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
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(noti_cse.this);
progressDialog.setMessage("On the Way!!!");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
try {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
private class CustomWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!DetectConnection.checkInternetConnection(noti_cse.this)) {
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
} else {
view.loadUrl(url);
}
return true;
}
}
#Override
protected boolean useDrawerToggle() {
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_placements)
return true;
if (item.getItemId() == android.R.id.home)
onBackPressed();
return super.onOptionsItemSelected(item);
}
You are setting 2 WebViewClient.
First:
webView.setWebViewClient(new CustomWebViewClient());
And after that, you are calling
startWebView()
which sets a new WebviewClient.
You can change your method like below:
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) {
if (!DetectConnection.checkInternetConnection(noti_cse.this)) {
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
} else {
view.loadUrl(url);
}
return true;
}
//Show loader on url load
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(noti_cse.this);
progressDialog.setMessage("On the Way!!!");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
super.onPageStarted(view, url, favicon);
}
public void onPageFinished(WebView view, String url) {
try {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
And remove this line form onCreate() method:
webView.setWebViewClient(new CustomWebViewClient());

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

Categories

Resources