我正在尝试通过webView中的触发器执行AdMob添加,但我无法访问该方法。它一直要求我让方法保持静态,但如果我这样做,我就无法访问我的一个变量。
MainActivity.java
public class MainActivity extends AppCompatActivity {
private InterstitialAd mInterstitialAd;
private WebView mWebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_MainActivity);
MobileAds.initialize(this, "ca-app-pub-XXXXXXXXXXXXXXXX~XXXXXXXXXX");
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-XXXXXXXXXXXXXXXX/XXXXXXXXXX");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mWebView = (WebView) findViewById(R.id.MainActivity);
mWebView.addJavascriptInterface(new WebAppInterface(this), "android");
}
public void displayAd() {
[Ad Code Here]
}
}
WebAppInterface.java
public class WebAppInterface {
Context mContext;
WebAppInterface(Context c) {
mContext = c;
}
@JavascriptInterface
public void ad() {
MainActivity.displayAd();
}
}
此代码无效。如何更改它以使其有效?
答案 0 :(得分:0)
试试这个。
public class WebAppInterface {
MainActivity mainActivity;
WebAppInterface(MainActivity mainActivity) {
this.mainActivity= mainActivity;
}
@JavascriptInterface
public void ad() {
mainActivity.displayAd();
}
}
并将活动引用传递给接口,如
mWebView.addJavascriptInterface(new WebAppInterface(MainActivity.this), "android");