如何从Webview加载插页式广告

时间:2017-03-08 17:22:24

标签: javascript android webview android-webview google-admob

我是android的新手,最近我开发了一个在WebView上运行的应用程序意味着在我的活动中我通过html,js页面将webview加载到webview上来进行gamin活动。

我的请求是“如何从网页文件加载插页式广告(html,js)”我搜索了与Ionic App相关的大部分建议,但我的应用与AndroidStudio相关。 所以请帮忙

2 个答案:

答案 0 :(得分:0)

你好这是代码......



awk '{ if (NR != $1) {print NR; exit 1} }' file.txt
4




答案 1 :(得分:0)

从WebView加载广告并不是那么简单但可以完成。让我们来看下面的例子:

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