我试图将Admob非页内广告添加到我的Android应用中,当有人离开活动时显示该应用。
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
public class Banner extends Activity {
/**
* Your ad unit id, you must replace it with your actual ad unit id Which
* you can generate from Admob website
*
*/
private static final String AD_UNIT_ID = "MY ADD UNIT ID";
private static final String TAG = "ExampleActivity";
private InterstitialAd iAd;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.banner);
iAd = new InterstitialAd(this);
iAd.setAdUnitId(AD_UNIT_ID);
iAd.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
Log.d(TAG, "onAdLoaded");
Toast.makeText(Banner.this, "Ad loaded successfully",
Toast.LENGTH_SHORT).show();
}
@Override
public void onAdFailedToLoad(int errorCode) {
String errorMessage = String.format("Failed to load add : "
+ getErrorReason(errorCode));
Log.d(TAG, errorMessage);
Toast.makeText(Banner.this, errorMessage,
Toast.LENGTH_SHORT).show();
}
});
loadInterstitial();
}
public void loadInterstitial() {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice(
"You can add you device id here, run code once and get id from logs")
.build();
iAd.loadAd(adRequest);
}
public void showInterstitial() {
if (iAd.isLoaded()) {
iAd.show();
} else {
Log.d(TAG, "Interstitial ad is not loaded yet");
}
}
/**
* Gets a string error reason from an error code
*
* @param errorCode
* @return
*/
private String getErrorReason(int errorCode) {
String errorReason = "unknown error";
switch (errorCode) {
case AdRequest.ERROR_CODE_INTERNAL_ERROR:
errorReason = "internal error";
break;
case AdRequest.ERROR_CODE_INVALID_REQUEST:
errorReason = "invalid request";
break;
case AdRequest.ERROR_CODE_NETWORK_ERROR:
errorReason = "network Error";
break;
case AdRequest.ERROR_CODE_NO_FILL:
errorReason = "no fill";
break;
}
return errorReason;
}
@Override
protected void onDestroy() {
showInterstitial();
super.onDestroy();
}
}
非页内广告加载成功,但我得到一个这样的空白屏幕(我等了1-2分钟,但仍然没有广告节目):
我仔细检查了我的AD_UNIT_ID。可能是什么问题呢?这是正常的吗?我还处于开发阶段,所以当我在Play商店上传我的应用程序时,这会得到纠正吗?
答案 0 :(得分:1)
你永远不会让它发挥作用。
在您的活动被销毁时,插页式广告没有上下文。而是在您的应用中找到一个自然断点,然后显示插页式广告。
答案 1 :(得分:0)
@Rushil如果Banner不是你的基本活动,那么你可以使用像这样的startActivityForResult()方法启动Banner Activity
Intent intent = new Intent(MainActivity.this, Banner.class);
startActivityForResult(intent,0);
然后在OnActivityResult函数中显示广告
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==0||resultCode==Activity.RESULT_OK)
{
if (iAd.isLoaded())
{
iAd.show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
希望这会有所帮助:)