I'm trying to show interstitial ads in some urls of my webview app, including onPagefinished and url.contains, but it doesn´t work. Here's my code:
#SuppressLint("SetJavaScriptEnabled") public class Juego extends ActionBarActivity {
/** ID intersticial */
private InterstitialAd interstitialAd;
private static final String AD_UNIT_ID = "ca-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_juego);
//Página web enlazada:
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://xxxxxxxxxxxxxxxxx.php");
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient());
myWebView.setVerticalScrollBarEnabled(false);
myWebView.setHorizontalScrollBarEnabled(false);
//Barra de progreso
final Activity activity = this;
final ProgressDialog progressDialog = new ProgressDialog(activity);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
myWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressDialog.setTitle("Cargando");
progressDialog.setMessage("Por favor espera");
progressDialog.show();
progressDialog.setProgress(0);
activity.setProgress(progress * 1);
progressDialog.incrementProgressBy(progress);
if(progress == 100 && progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
public void onPageFinished (WebView view, String url) {
// Anuncios intersticiales: Create the interstitial.
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(AD_UNIT_ID);
// Create ad request.
AdRequest adRequest = new AdRequest.Builder().build();
// Begin loading your interstitial.
interstitialAd.loadAd(adRequest);
if (url.contains("game")) {
interstitialAd.show();
}
}
}
Any help?
use this
public void onPageFinished (WebView view, String url) {
interstitial = new InterstitialAd(this);
interstitial.setAdUnitId("ca-app-pub-5236990339136194/xxxxxxxxxx");
// Begin loading your interstitial.
interstitial.loadAd(adRequest);
interstitial.setAdListener(new AdListener(){
public void onAdLoaded(){
displayInterstitial();
}
// Invoke displayInterstitial() when you are ready to display an interstitial.
public void displayInterstitial() {
if (interstitial.isLoaded()) {
interstitial.show();
}
}
} );
}
and don't forget add this on your onCreate blog
AdView adView = (AdView) this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
Related
I have implemented following code for interstitial ads .Problem I am facing is that interstitial ad is shown only on first URL click. I want to adjust ads on every URL click or every 5th URL click in WebView app .Help in this regard will highly be appreciated. Following is the code i want to be modified .
private WebView webview;
private AdView mAdView;
private InterstitialAd mInterstitialAd;
SwipeRefreshLayout mySwipeRefreshLayout;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {}
});
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i("TAG", "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i("TAG", loadAdError.getMessage());
mInterstitialAd = null;
}
});
private class WebViewClientDemo extends WebViewClient {
#Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null) {
mInterstitialAd.show(MainActivity.this);
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
return super.shouldOverrideUrlLoading(view, url);
}
You need to load Ad after each show. Create a static counter variable to load it on everyth nth click.
static int instanceCounter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoadInterstitial();
}
private void LoadInterstitial(){
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this,"ca-app-pub-3940256099942544/1033173712", adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i("TAG", "onAdLoaded");
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i("TAG", loadAdError.getMessage());
mInterstitialAd = null;
}
});
}
private class WebViewClientDemo extends WebViewClient {
#Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null && isDisplayAdvert()) {
mInterstitialAd.show(MainActivity.this);
LoadInterstitial();
} else {
Log.d("TAG", "The interstitial ad wasn't ready yet.");
}
return super.shouldOverrideUrlLoading(view, url);
}
private bool isDisplayAdvert(){
instanceCounter++;
if(instanceCounter==5){
instanceCounter = 0;
return true;
}
return false;
}
Thanks sir Amod Gokhale . I tried the following code and it is working too .
Would you recommend me about the better one between both codes .
private class WebViewClientDemo extends WebViewClient {
int n = 1;
#Override
//Keep webview in app when clicking links
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (mInterstitialAd != null) {
if( n%6 == 0 )
{
mInterstitialAd.show(MainActivity.this);
} n++;
}
LoadInterstitial();
return super.shouldOverrideUrlLoading(view, url);
}
If I have created a deep link using the branch.io that opens a specific screen in my app. If this link is also available in my app and a user clicks on it, will it open my screen? or it will do nothing as the link I am trying to open from the app is pointing to the same app?
When you click on a Branch link within a webView in your App, you will have to handle the routing to the specific Activity, after reading the Branch link parameters.
Here is a sample Activity which contains a webView and and shows a couple of Branch links. When you click on a link in the webView it reopens the webview and displays the link parameters in a Toast message if a Branch link is clicked
public class MainActivity extends AppCompatActivity {
private WebView webView_;
private Button button_;
private String TAG = "WebViewController";
private Context context_;
private static final String URL_TO_LOAD = "https://evangelosg.github.io/index.html";
private static final String BRANCH_LINK_TO_LOAD = "https://ere6.app.link/b6sS0gsCfG";
#Override
protected void onNewIntent(Intent intent) {
Log.d("WebView", "onNewIntent");
setIntent(intent);
}
#Override
protected void onResume() {
super.onResume();
Branch branch = Branch.getInstance();
branch.initSession(new Branch.BranchReferralInitListener() {
#Override
public void onInitFinished(JSONObject referringParams, BranchError error) {
if (error == null) {
Log.d(TAG, referringParams.toString());
Toast.makeText(context_, referringParams.toString(), Toast.LENGTH_LONG).show();
if (referringParams.has(BundleExtraKeys.CLICKED_BRANCH_LINK)) {
try {
boolean clickedBranchLink = referringParams.getBoolean(BundleExtraKeys.CLICKED_BRANCH_LINK);
if (clickedBranchLink) {
//do stuff!
}
} catch (JSONException e) {
Log.d("BranchTrends", e.getMessage());
}
}
} else {
Log.i("MyApp", error.getMessage());
}
}
}, this.getIntent().getData(), this);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context_ = this;
setContentView(R.layout.activity_main);
webView_ = (WebView) findViewById(R.id.webView);
webView_.setWebViewClient(new BranchWebViewController("app.link", MainActivity.class));
webView_.loadUrl(URL_TO_LOAD);
button_ = (Button) findViewById(R.id.button);
button_.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.intent.putExtra("branch", BRANCH_LINK_TO_LOAD);
customTabsIntent.intent.putExtra("branch_force_new_session", true);
finish();
customTabsIntent.launchUrl(MainActivity.this, Uri.parse(BRANCH_LINK_TO_LOAD));
}
});
}
public class BranchWebViewController extends WebViewClient {
private String myDomain_;
private Class activityToLaunch_;
BranchWebViewController(#NonNull String myDomain, Class activityToLaunch) {
myDomain_ = myDomain;
activityToLaunch_ = activityToLaunch;
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.contains(myDomain_)) {
Intent i = new Intent(view.getContext(), activityToLaunch_);
i.putExtra("branch", url);
i.putExtra("branch_force_new_session", true);
finish();
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
}
}
}
Once you read the link parameters you can route to the appropriate Activity based on the link parameters.
I have a list of webview to show different pdf's, I need to show it in a horizontal RecyclerView, but the problem is that when I scroll it horizontally then the coming webview just goes on top of the current one and the current one instead of shifting to the left hand side, it remains at its position. It looks a little weird.
This is my RecyclerViewAdapter
public class HorizontalManual extends RecyclerView
.Adapter {
Context context;
private ArrayList<String> list;
public class DataObjectHolder extends RecyclerView.ViewHolder {
ImageView imgUploaded;ProgressBar loader; WebView webViewManual;
public DataObjectHolder(View itemView) {
super(itemView);
webViewManual = (WebView) itemView.findViewById(R.id.pdf_manual_webView);
}
}
public HorizontalManual(Context context, ArrayList<String> list) {
this.context = context;
this.list = list;
}
#Override
public DataObjectHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View view = null;
try {
view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.horz_pdf, parent, false);
if (view.getLayoutParams ().width == RecyclerView.LayoutParams.MATCH_PARENT)
view.getLayoutParams ().width = parent.getWidth ();
} catch (Exception e) {
e.printStackTrace();
}
return new DataObjectHolder(view);
}
#Override
public void onBindViewHolder(final DataObjectHolder holder, final int position) {
String url = "http://docs.google.com/gview?embedded=true&url=" + list.get(position);
Log.e("pdf",url);
WebSettings websettings = holder.webViewManual.getSettings();
websettings.setJavaScriptEnabled(true);
holder.webViewManual.loadUrl(url);
holder.webViewManual.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
holder.webViewManual.loadUrl("javascript:(function() { " +
"document.getElementsByClassName('ndfHFb-c4YZDc-GSQQnc-LgbsSe ndfHFb-c4YZDc-to915-LgbsSe VIpgJd-TzA9Ye-eEGnhe ndfHFb-c4YZDc-LgbsSe')[0].style.display='none'; })()");
}
});
holder.webViewManual.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
holder.webViewManual.setHorizontalScrollBarEnabled(false);
}
#Override
public int getItemCount() {
return list.size();
}
}
I'm setting the HorizontalList in my Fragment like this:
mRecyclerViewManual.setHasFixedSize(true);
rLayoutManagerManual = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false); mRecyclerViewManual.setLayoutManager(rLayoutManagerManual);
//Setting adapter
HorizontalManual setUploadsListAdapterManual = new HorizontalManual(context, list); mRecyclerViewManual.setAdapter(setUploadsListAdapterManual);
Load you google doc url using iframe tag as shown below.
String frameVideo = "<html><body>Youtube video .. <br> <iframe width=\"320\" height=\"315\" src=\"https://docs.google.com/gview?embedded=true&url=http://Dealerapp.ebunch.ca/upload/wl/manuals/7.pdf\" frameborder=\"0\" allowfullscreen></iframe></body></html>";
holder.webView.loadData(frameVideo, "text/html", "utf-8");
I'm using RoboVM bindings for my iOS application to display AdMob interstitials. When I close the interstitial ad, I lose all touch controls. Is there a way to detect the ad being closed so I can put the touch back to the game? Or is there a better way to implement interstitials? Here's my code below:
public class IOSLauncher extends IOSApplication.Delegate implements IActivityRequestHandler{
private static final Logger log = new Logger(IOSLauncher.class.getName(), Application.LOG_DEBUG);
private IOSApplication iosApplication;
//interstitial
private static final String INTERSTITIAL_AD = "MY_AD_ID";
private GADInterstitial interstitial;
private UIWindow window;
private UIViewController rootViewController;
#Override
protected IOSApplication createApplication() {
IOSApplicationConfiguration config = new IOSApplicationConfiguration();
config.orientationLandscape = true;
config.orientationPortrait = false;
iosApplication = new IOSApplication(new PaperPig(this), config);
return iosApplication;
}
public static void main(String[] argv) {
NSAutoreleasePool pool = new NSAutoreleasePool();
UIApplication.main(argv, null, IOSLauncher.class);
pool.close();
}
#Override
public void initializeAds() {
intializeInterstitial();
}
public void intializeInterstitial () {
rootViewController = new UIViewController();
interstitial = new GADInterstitial();
interstitial.setAdUnitID(INTERSTITIAL_AD);
interstitial.setDelegate(new GADInterstitialDelegateAdapter() {
#Override
public void didReceiveAd (GADInterstitial ad) {
System.out.println("Did receive ad.");
}
#Override
public void didFailToReceiveAd (GADInterstitial ad, GADRequestError error) {
System.out.println(error.description());
System.out.println(error.getErrorCode());
}
});
window = new UIWindow(UIScreen.getMainScreen().getBounds());
window.setRootViewController(rootViewController);
window.addSubview(rootViewController.getView());
interstitial.loadRequest(GADRequest.create());
}
#Override
public void showOrLoadInterstital() {
if (interstitial.isReady()) {
if (rootViewController == null) {
rootViewController = new UIViewController();
}
if (window == null) {
window = new UIWindow(UIScreen.getMainScreen().getBounds());
window.setRootViewController(rootViewController);
}
window.makeKeyAndVisible();
interstitial.present(rootViewController);
}
//Return touch back to Game
//UIApplication.getSharedApplication().getKeyWindow().setRootViewController(rootViewController);
}
}
You need to call:
window.setHidden(true);
Change your creation of GADInterstitialDelegateAdapter() to the following
interstitial.setDelegate(new GADInterstitialDelegateAdapter() {
#Override
public void didReceiveAd (GADInterstitial ad) {
System.out.println("Did receive ad.");
}
#Override
public void didDismissScreen(GADInterstitial ad) {
window.setHidden(true);
}
#Override
public void didFailToReceiveAd (GADInterstitial ad, GADRequestError error) {
System.out.println(error.description());
System.out.println(error.getErrorCode());
}
});
Here is My Code.
I just want to get the page content from the Webview after load the URL .
On Android, I have a WebView that is displaying a page.
How do I get the page source without requesting the page again?
It seems WebView should have some kind of WebResourceResponse () method in Android 3.0 but don't know how to use it.
public class WebActivity extends Activity {
WebView mWebView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("https://xyz.com");
mWebView.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient {
public WebResourceResponse shouldInterceptRequest (WebView view, String url)
{
return null;
}
#Override
public void onPageFinished(WebView view, String url)
{
/* This call inject JavaScript into the page which just finished loading. */
mWebView.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}}
I know this is old, but for future visitors, the following should work.
First, you need to define an interface such as:
final class LoadingInterface {
#JavascriptInterface
public void outputHTML(final String html){
//do what ever you want with html
}
}
Then on your WebView call
webView.addJavascriptInterface(new LoadingInterface(), "INTERFACE");
In onPageFinished put:
String js = "javascript:"
+"var html = document.getElementsByTagName('html')[0].innerHTML;"
+"window.INTERFACE.outputSchedule(html);";
webView.loadUrl(js);
If you only need part of a page, you can replace getElementsByTagName('html')[0] with something like getElementById('partOfPage')