How to Load Interstitial Ads from Webview - javascript

I am new to android, recently I developed an application which runs on WebView means in my activity I placed a webview doing the gamin activity through html,js pages by loading those to webview.
Here my request is "How to load the Interstitial Ads from the webpage files(html,js) I googled most of the suggestions related to Ionic App but my app is AndroidStudio related.
so please help

Loading an ad from WebView isn't that straightforward but could be done. So let's take the following example:
class MainActivity extends AppCompatActivity {
protected InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// load interstitial ad
mInterstitialAd = new InterstitialAd(getContext());
mInterstitialAd.setAdUnitId("YOUR_AD_ID");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
WebView browser = findViewById(R.id.webview);
browser.addJavascriptInterface(new InterceptorJavaScript(context), "Interceptor");
WebSettings webSettings = browser.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
browser.setWebViewClient(new CapturingWebViewClient());
browser.loadUrl("http://website.com");
}
/**
* This class will handle all JS events from the UI back to
* Java code and will trigger the Interstitial ad
*/
private class InterceptorJavaScript {
Context webViewContext;
/**
* Instantiate the interface and set the context
*/
InterceptorJavaScript(Context webView) {
webViewContext = webView;
}
#JavascriptInterface
#SuppressWarnings("unused")
public void startInterstitial() {
// we need to run it on the main UI thread
Handler mHandler = new Handler(Looper.getMainLooper());
mHandler.post(new Runnable() {
#Override
public void run() {
if (MainActivity.mInterstitialAd.isLoaded()) {
MainActivity.mInterstitialAd.show();
}
// preload new ad
BrowserFragment.mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
}
}
private class CapturingWebViewClient extends WebViewClient {
/**
* This method will inject the JavaScritp that will trigger
* your Java code and show the interstitial in the main UI thread
*/
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl(
"javascript:Interceptor.startInterstitial();"
);
// Attach JS event to your button so you can call the JS function. I've used jQuery just for simplicity
view.loadUrl(
"javascript:$('#btn').on('click', function(){ Interceptor.startInterstitial(); });"
);
}
}
}

hello this is the code....
import android.os.Bundle; import android.view.Window; import android.view.WindowManager;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
public class a4 extends AppCompatActivity {
AdView mAdView;
InterstitialAd mInterstitialAd;
WebView WebViewWithCSS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_a4);
WebViewWithCSS = (WebView)findViewById(R.id.webView);
WebSettings webSetting = WebViewWithCSS.getSettings();
webSetting.setJavaScriptEnabled(true);
WebViewWithCSS.setWebViewClient(new WebViewClient());
WebViewWithCSS.loadUrl("file:///android_asset/4.html");
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
mAdView.loadAd(adRequest);
mInterstitialAd = new InterstitialAd(this);
// set the ad unit ID
mInterstitialAd.setAdUnitId(getString(R.string.interstitial_full_screen));
adRequest = new AdRequest.Builder()
.build();
// Load ads into Interstitial Ads
mInterstitialAd.loadAd(adRequest);
mInterstitialAd.setAdListener(new AdListener() {
public void onAdLoaded() {
showInterstitial();
}
});
}
#Override
public void onPause() {
if (mAdView != null) {
mAdView.pause();
}
super.onPause();
}
#Override
public void onResume() {
super.onResume();
if (mAdView != null) {
mAdView.resume();
}
}
#Override
public void onDestroy() {
if (mAdView != null) {
mAdView.destroy();
}
super.onDestroy();
}
private void showInterstitial() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
}
}

Related

Closing dialog inside shouldOverrideUrlLoading() or ignoring in project, when is custom url open

I am trying to auth google user in WebView, I found a good solution for these days, it works fine for google login, but I cannot disable dialog in other urls like (, sms: , smsto:)
Example Situation: User click on telephone number in my app, it will open the phone dial, but when he returns back.. there is a empty dialog window with close button, i use it for google login with JS.
How can i close this dialog message inside the shouldOverrideUrlLoading()? Or is there any better solution to not open other links in the dialog? How can i improve my code to solve my problem? Thank you guys!
package com.example.app;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslCertificate;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.URLUtil;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.lang.reflect.Field;
import java.security.cert.X509Certificate;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class MainActivity extends Activity {
private WebView mWebView;
private String userAgent;
private Context contextPop;
private WebView webViewPop;
private AlertDialog builder;
#Override
#SuppressLint("SetJavaScriptEnabled")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userAgent = System.getProperty("http.agent");
mWebView = findViewById(R.id.activity_main_webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setAppCacheEnabled(false);
webSettings.setAllowFileAccess(true);
webSettings.setAllowFileAccessFromFileURLs(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
webSettings.setUserAgentString(userAgent+ "com.example.app");
mWebView.clearCache(true);
// REMOTE RESOURCE
mWebView.loadUrl("https://example.eu/");
mWebView.setWebChromeClient(new CustomChromeClient());
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
contextPop = this.getApplicationContext();
// LOCAL RESOURCE
// mWebView.loadUrl("file:///android_asset/index.html");
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
final Context myApp = this;
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) {
String host = Uri.parse(url).getHost();
if (url.startsWith("tel:") || url.startsWith("sms:") || url.startsWith("smsto:") || url.startsWith("mms:") || url.startsWith("mmsto:"))
{
webViewPop.destroy();
Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
startActivity(intent);
return true;
}
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//view.getContext().startActivity(intent);
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(mWebView, 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());
}
}
#Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
new AlertDialog.Builder(myApp)
.setMessage(message)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
result.confirm();
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
result.cancel();
}
})
.setCancelable(false)
.create()
.show();
return true;
}
#Override
public boolean onJsAlert(WebView view, final String url, String message,
JsResult result) {
new AlertDialog.Builder(myApp)
.setMessage(message)
.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
arg0.dismiss();
}
})
.setCancelable(false)
.show();
result.cancel();
return true;
}
}
}

Call MainActivity method from another class in android

I'm working on an android app. I want to pass some value from my webview to my android application.
I solved this problem successfully by using the solution given in Passing data from java class to Web View html.
The problem that I'm facing is when I'm trying to call MainActivity methods from JavaScriptInterface.java, the methods are not being called or no errors are given.
here's what I have tried so far:
MainActivity act=new MainActivity();
act.myMethod() //This method is available in my activity
but it is not being called.
and
((MainActivity)getActivity).myMethod();
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.AppTheme);
setContentView(R.layout.activity_main);
}
public void myMethod() {
Toast.makeText(this, "Inside MainActivity", Toast.LENGTH_SHORT).show();
}
}
//JavaScriptInterface class
class JavaScriptInterface {
Context mContext;
JavaScriptInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
#JavascriptInterface
public void onButtonClick(String toast1, String toast2) {
Toast.makeText(mContext, toast1+" | "+toast2, Toast.LENGTH_SHORT).show(); //THIS IS WORKING
MainActivity act=new MainActivity();
act.myMethod(); //NOT WORKING
}
}
Technically, the myMethod will get called, but since you create the MainActivity yourself, it's not attached to anything.
In general, you shouldn't create a new MainActivity instance this way. To open a new MainActivity, you use an Intent.
In your case, you should have a reference to the original MainActivity instance, and call this method there. Not create a new one in any way, as you already have it running.
An easy way to solve it:
MainActivity.this.myMethod("Hello there")
You don't have to store mContext . You already are inside of MainActivity.
So, the full code would be:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = findViewById(R.id.webview);
myWebView.loadUrl("http://www.google.com");
myWebView.addJavascriptInterface(new WebAppInterface(), "Android");
}
public void myMethod(String test){
Toast.makeText(this, test, Toast.LENGTH_SHORT).show();
}
public class WebAppInterface {
/** Show a toast from the web page */
#JavascriptInterface
public void showToast(String toast) {
MainActivity.this.myMethod("Hello there");
}
}
}
In fact, I think you can even avoid having the MainActivity.this. , and call myMethod directly.
You are creating another object of MainActivity this is why its not getting displayed. You are passing the activity context to the interface so you can just
((MainActivity)mContext).myMethod();
Sample MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = findViewById(R.id.webview);
myWebView.loadUrl("http://www.google.com");
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
}
public void myMethod(String test){
Toast.makeText(this, test, Toast.LENGTH_SHORT).show();
}
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
#JavascriptInterface
public void showToast(String toast) {
((MainActivity)mContext).myMethod("hello");
}
}
}
Check out android documentation for more info

App not getting longitude and latitude from HTML and JAVA script

I have a simple APP that calls a HTTPS page and latitude and longitude don't work when calling https://www.mypage.com/getlonlat.html from within my APP. It works when calling page from IE, Chrome, Firefox ect. getlonlat.html has javascript that uses GeoLocation to calculate longitude and latitude. This page HAS a valid SSL.
package com.mywebsite.webview;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class GeoWebViewActivity extends Activity {
public class GeoWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public class GeoWebChromeClient extends WebChromeClient {
#Override
public void onGeolocationPermissionsShowPrompt(String origin,
GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
}
}
WebView mWebView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webView1);
mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
mWebView.setWebViewClient(new GeoWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setGeolocationEnabled(true);
mWebView.setWebChromeClient(new GeoWebChromeClient());
mWebView.loadUrl("https://www.mywebsite.com");
if (mWebView.canGoBack()) {
mWebView.goBack();
}
}
#Override
public void onBackPressed() {
// Pop the browser back stack or exit the activity
if (mWebView.canGoBack()) {
mWebView.goBack();
}
else {
super.onBackPressed();
}
}
private void postUrl(byte[] postData,
String url) { mWebView.goBack();
}
}
Index.html
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position) {
document.getElementById("getlat").value = position.coords.latitude;
document.getElementById("getlon").value = position.coords.longitude;
}
</script>
As it turns out, my SSL certificate was not set up properly with my hosting company. The code above works perfectly now. How nifty, call a HTML, PHP, JAVA page from an APP without having to re-write the whole page in android.

Can I show progress dialog and error message while parsing XML using JavaScript?

I am developing android web application for a blog like website.
For this I am showing HTML page contenting list of categories which when clicked shows articles related to that category.
I am fetching this articles from website's RSS feeds which is in XML format and by using JavaScript I am parsing it to display on HTML page.
This process of parsing XML takes lot of time to load a page.During this period I am getting blank screen.I have implemented progress dialog which works fine when page is loading for the first time but when XML is getting parsed by JavaScript it does not appear.
Here is how I implemented Process dialog.
Activity.java:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.setBackgroundColor(0);
final ProgressDialog progressDialog = new ProgressDialog(activity);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...please wait");
progressDialog.setCancelable(true);
webview.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webview.loadUrl("file:///android_asset/HomePage.html");
// WebChromeClient give progress etc info
webview.setWebChromeClient(new WebChromeClient()
{
public void onProgressChanged(WebView view, int progress)
{
progressDialog.show();
progressDialog.setProgress(0);
activity.setProgress(progress * 1000);
progressDialog.incrementProgressBy(progress);
if (progress == 100 && progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
How can I show progress dialog while XML is being parsed by JavaScript?
Also I want to show an error message if no internet connectivity available for same thing is their any way to do so?
I have used call function as "tel:phone number" which was working but after I added de
public boolean shouldOverrideUrlLoading it is not working? what's i done wrong?
for your questions You can use following code in your activity.java file
package com.package name;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;
public class Myactivity extends Activity {
TextView myLabel;
WebView wv;
final Activity activity=this;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_PROGRESS,Window.PROGRESS_VISIBILITY_ON);
wv=(WebView)findViewById(R.id.webview);
wv.getSettings().setJavaScriptEnabled(true);
wv.setBackgroundColor(0);
final ProgressDialog progressDialog = new ProgressDialog(activity);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...please wait");
progressDialog.setCancelable(true);
wv.setWebViewClient(new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL,
Uri.parse(url));
startActivity(intent);
return true;
}else{
view.loadUrl(url);
return true;
}
}
});
wv.loadUrl("file:///android_asset/page.html");
// WebChromeClient give progress etc info
wv.setWebChromeClient(new WebChromeClient()
{
public void onProgressChanged(WebView view, int progress)
{
progressDialog.show();
progressDialog.setProgress(0);
activity.setProgress(progress * 1000);
progressDialog.incrementProgressBy(progress);
if (progress == 100 && progressDialog.isShowing())
progressDialog.dismiss();
}
});
if (AppStatus.getInstance(this).isOnline(this)) {
Toast t = Toast.makeText(this,"Welcome !!!!",8000);
t.show();
} else {
AlertDialog alertDialog = new AlertDialog.Builder(
CafeNashikActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("No Internet");
// Setting Dialog Message
alertDialog.setMessage("Internet Connection not available!");
// Setting Icon to Dialog
//alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MyActivity.this.finish();
}
});
// Showing Alert Message
alertDialog.show();
}
}
}
Hope this will help you.

Binding JavaScript code to Android code

Im trying to invoke a method in java from javascript, but this doesn't happen when I run the application in the emulator, the application stops when it is suppose to call the method in java. here is the java code:
import android.os.Bundle;
import android.webkit.WebView;
import com.phonegap.*;
public class App extends DroidGap {
WebView webView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webView = new WebView(this);
webView.addJavascriptInterface(new message(), "Show");
super.loadUrl("file:///android_asset/www/index.html");
}
class message {
String msg() {
return "Hello World!!";
}
}
}
here is the javascript:
<script type="text/javascript">
{
alert("Start");
alert(Show.msg());
alert("End");
}
</script>
It shows the first alert but nothing thereafter, can anyone help?
Your problem is that you're half using PhoneGap and half not. You're creating a separate WebView class from PhoneGap's. The WebView class that you added "Show" to never gets used. Instead the WebView class that is a member of the super (DroidGap) is.
You should do one of two things.
Use PhoneGap's plugin structure (see examples here)
Don't use PhoneGap at all and have a class that looks more like the following:
public class act extends Activity {
WebView webView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webView = new WebView(this);
webView.getSettings().setJavaScriptEnabled(true);
// Set JS alert() hook
webView.setWebChromeClient(new WebChromeClient() {
public boolean onJsAlert(WebView view, String url, String message, JsResult result)
{
return false;
}
});
webView.loadUrl("file:///android_asset/www/index.html");
// Add JS libraries
webView.addJavascriptInterface(new message(), "Show");
}
class message {
public String msg() {
return "Hello World!!";
}
}
}
Note that the method msg needs to be public
Why not just use AlertDialog?
private void showDialog(int title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(title);
builder.setMessage(message);
builder.setPositiveButton(R.string.ok_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
}

Categories

Resources