I am new in android studio, I have this code for showing interstitial.
Now I want to add timer before showing interstitial ad according admob policy.
but no idea how to add this. can someone help me out to do this?
private void goMainScreen(int position) {
if (mInterstitialAd != null) {
mInterstitialAd.show(this);
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdClicked() {
super.onAdClicked();
}
#Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
startActivity(new Intent(MainActivity.this, SignsActivity.class));
Pref.getInstance(MainActivity.this).setIndex(position);
}
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
super.onAdFailedToShowFullScreenContent(adError);
startActivity(new Intent(MainActivity.this, SignsActivity.class));
Pref.getInstance(MainActivity.this).setIndex(position);
}
#Override
public void onAdImpression() {
super.onAdImpression();
}
#Override
public void onAdShowedFullScreenContent() {
super.onAdShowedFullScreenContent();
}
});
} else {
startActivity(new Intent(MainActivity.this, SignsActivity.class).putExtra("index", position));
Pref.getInstance(MainActivity.this).setIndex(position);
}
adPosition = adPosition + 1;
}
Related
I'd like to show an interstitial ad while going from MainActivity to Activity2. Instead, the ad only shows when clicking back from Activity2 to the MainActivity.
Does anyone know what I've done wrong?
Thanks
I have a button in MainActivity that loads Activity2. I have the following in the code for the button.
if (mInterstitialAd != null) {
mInterstitialAd.show(MainActivity.this);
} else {
Log.i(TAG, "Ad failed to load");
}
I thought I could solve the problem by replacing MainActivity.this with Activity2, but it get a red underline. I've tried "Activity2," "Activity2.class" and "Activity2.java."
The below code is for loading and calling the ads.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(InitializationStatus initializationStatus) {
}
});
loadInterstitial();
public void loadInterstitial(){
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this, getString(R.string.interstitial_ad_unit_id), adRequest, new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
super.onAdLoaded(interstitialAd);
Log.d(TAG, "Ad loaded successfully");
mInterstitialAd = interstitialAd;
mInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback() {
#Override
public void onAdFailedToShowFullScreenContent(#NonNull AdError adError) {
super.onAdFailedToShowFullScreenContent(adError);
Log.d(TAG, "Ad failed to show");
}
#Override
public void onAdShowedFullScreenContent() {
super.onAdShowedFullScreenContent();
Log.d(TAG, "Ad shown successfully");
mInterstitialAd = null;
}
#Override
public void onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent();
Log.d(TAG, "Ad dismissed");
}
});
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
super.onAdFailedToLoad(loadAdError);
Log.i(TAG, "onAdLoaded");
mInterstitialAd = null;
}
});
}
I think you need to add changes like below way.
In MainActivity to write below code
Add constant
public static final int REQUEST_CODE = 1;
Call Activity2 like below way
Intent intent = new Intent(MainActivity.this,
Activity2.class);
startActivityForResult(intent , REQUEST_CODE);
Now use onActivityResult to retrieve the result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
loadInterstitial();
}
} catch (Exception ex) {
Toast.makeText(Activity.this, ex.toString(),
Toast.LENGTH_SHORT).show();
}
}
And Activity2 to write below code whenever you are press back
key/button action
Intent intent = getIntent();
intent.putExtra("key", value);
setResult(RESULT_OK, intent);
finish();
Here is the code in onAdClosed or onAdFailed method navigation is not working but in else part of the IF Statement it works
void NavigateFragmentTo(final View v, final int id) {
//Navigation.findNavController(v).navigate(id);
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
super.onAdClosed();
Navigation.findNavController(v).navigate(id);
Toast.makeText(app, "closed", Toast.LENGTH_SHORT).show();
RequestInterstitial();
}
#Override
public void onAdFailedToLoad(int i) {
super.onAdFailedToLoad(i);
Navigation.findNavController(v).navigate(id);
RequestInterstitial();
}
});
} else {
Navigation.findNavController(v).navigate(id);
}
}
You need to place a delay from when your callback completes to when you try to navigate. It seems that the Navigation component still needs time before it can actually navigate in some scenarios.
Add a delay to something like below
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
super.onAdClosed();
new Handler(Looper.getMainLooper()).postDelayed(() -> {
Navigation.findNavController(v).navigate(id);
}, 500);
Toast.makeText(app, "closed", Toast.LENGTH_SHORT).show();
RequestInterstitial();
}
#Override
public void onAdFailedToLoad(int i) {
super.onAdFailedToLoad(i);
new Handler(Looper.getMainLooper()).postDelayed(() -> {
Navigation.findNavController(v).navigate(id);
}, 500);
RequestInterstitial();
}
});
During the Rewarded video play i want to disable the back button and set a minimum waiting time . is it possible to do?On which function should i change to complete my desired functionality?
here is my code
if (mAd.isLoaded()) {
mAd.show();
} else {
startActivity(new Intent(EssayActivityQstnShow2.this, Essay_Answer_Show.class));
}
and here is Rewarded video ads handling methods
private void loadRewardedVideoAds() {
if (!mAd.isLoaded()) {
mAd.loadAd(getResources().getString(R.string.rewardedvideoid), new AdRequest.Builder().build());
}
}
#Override
public void onRewardedVideoAdLoaded() {
}
#Override
public void onRewardedVideoAdOpened() {
// onBackPressed();
}
#Override
public void onRewardedVideoStarted() {
// onBackPressed();
}
#Override
public void onRewardedVideoAdClosed() {
startActivity(new Intent(EssayActivityQstnShow2.this, Essay_Answer_Show.class));
}
#Override
public void onRewarded(RewardItem rewardItem) {
}
#Override
public void onRewardedVideoAdLeftApplication() {
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
loadRewardedVideoAds();
}
#Override
public void onRewardedVideoCompleted() {
startActivity(new Intent(EssayActivityQstnShow2.this, Essay_Answer_Show.class));
}
Try below code
private boolean isVideoPlaying;
#Override
public void onRewardedVideoStarted() {
isVideoPlaying = true;
}
#Override
public void onRewardedVideoAdClosed() {
isVideoPlaying = false;
}
and than onBackPress() check, if the video is playing or not
#Override
public void onBackPressed() {
if (!isVideoPlaying)
super.onBackPressed();
}
Before implementing this, please read the policies carefully.
You must override the onBackPressed callback in activity and remove line super.onBackPressed(). then if the user taps the back button the activity will not close.
If you have no access to the Essay_Answer_Show activity check can you create another activity which extends that or clone library and tries to modify activity?
This is my reward video code. What i want to do is a button with every click loads a reward video. The problems that faced me are, first the reward video loading takes much time to load and second the reward video sometimes is requested only once so what is the right way to start a reward video on every click with no delay?
rewardedVideoAd = MobileAds.getRewardedVideoAdInstance(MainActivity.this);
rewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917", new AdRequest.Builder().build());
rewardedVideoAd.setRewardedVideoAdListener(new RewardedVideoAdListener() {
#Override
public void onRewarded(RewardItem reward) {
}
#Override
public void onRewardedVideoAdLeftApplication() {}
#Override
public void onRewardedVideoAdClosed() {}
#Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {
rewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",new AdRequest.Builder().build());
}
#Override
public void onRewardedVideoAdLoaded() {}
#Override
public void onRewardedVideoAdOpened() {}
#Override
public void onRewardedVideoStarted() {
rewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",new AdRequest.Builder().build());
}
});
and this is my button on click code
if (rewardedVideoAd.isLoaded()){
rewardedVideoAd.show();
}
i can shows video reward ads (only test ads) using below code.
public class MainActivity extends AppCompatActivity implements RewardedVideoAdListener {
private RewardedVideoAd mRewardedVideoAd;
private InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MobileAds.initialize(this, getResources().getString(R.string.app_id));
// Use an activity context to get the rewarded video instance.
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",
new AdRequest.Builder().build());
//getResources().getString(R.string.Video_reward_ad_unit_id)
mRewardedVideoAd.setRewardedVideoAdListener(this);
findViewById(R.id.btVideo).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
}
});
mInterstitialAd = new InterstitialAd(MainActivity.this);
mInterstitialAd.setAdUnitId(getResources().getString(R.string.banner_ad_unit_id));
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
// Load the next interstitial.
mInterstitialAd.loadAd(new AdRequest.Builder().build());
mInterstitialAd.show();
}
});
findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
});
}
#Override
protected void onStart() {
loadTestRewardedVideoAd();
MobileAds.setAppMuted(true);
super.onStart();
}
private void loadTestRewardedVideoAd() {
mRewardedVideoAd.loadAd("ca-app-pub-3940256099942544/5224354917",
new AdRequest.Builder().build());
}
#Override
public void onRewardedVideoAdLoaded() {
Log.i("onRewardedVideoAdLoaded", "Ad Loaded");
}
#Override
public void onRewardedVideoAdOpened() {
Toast.makeText(this, "Ad OPEPED Now ", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoStarted() {
}
#Override
public void onRewardedVideoAdClosed() {
}
#Override
public void onRewarded(RewardItem reward) {
}
#Override
public void onRewardedVideoAdLeftApplication() {
Log.i("onRewardedVideoAdLeft", "END");
}
#Override
public void onRewardedVideoAdFailedToLoad(int i) {
Log.i("onRewardedVideoAdLeft", "END");
}
but this is only works with test device not on real device.
My code is here
I have test it on my device I also integrate this app on firebase.
but it never go to onRewarded it always call onRewardedFaild why sir?
can anyone help me.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize the Mobile Ads SDK.
MobileAds.initialize(this,APP_ID);
mRewardedVideoAd = MobileAds.getRewardedVideoAdInstance(this);
mRewardedVideoAd.setRewardedVideoAdListener(this);
loadRewardedVideoAd();
// Create the "retry" button, which tries to show an interstitial between game plays.
mRetryButton = ((Button) findViewById(R.id.retry_button));
mRetryButton.setVisibility(View.INVISIBLE);
mRetryButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startGame();
}
});
// Create the "show" button, which shows a rewarded video if one is loaded.
mShowVideoButton = ((Button) findViewById(R.id.watch_video));
mShowVideoButton.setVisibility(View.INVISIBLE);
mShowVideoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showRewardedVideo();
}
});
// Display current coin count to user.
mCoinCountText = ((TextView) findViewById(R.id.coin_count_text));
mCoinCount = 0;
mCoinCountText.setText("Coins: " + mCoinCount);
startGame();
}
#Override
public void onPause() {
super.onPause();
pauseGame();
mRewardedVideoAd.pause(this);
}
#Override
public void onResume() {
super.onResume();
if (!mGameOver && mGamePaused) {
resumeGame();
}
mRewardedVideoAd.resume(this);
}
private void pauseGame() {
mCountDownTimer.cancel();
mGamePaused = true;
}
private void resumeGame() {
createTimer(mTimeRemaining);
mGamePaused = false;
}
private void loadRewardedVideoAd() {
if (!mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.loadAd(AD_UNIT_ID, new AdRequest.Builder().build());
/* AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("40C4DDA8F53FFA9BA5B61261E0CA28AB") // Test devices don't work work with rewarded video ads.
.build();
mRewardedVideoAd.loadAd(AD_UNIT_ID, adRequest);*/
}
}
private void addCoins(int coins) {
mCoinCount = mCoinCount + coins;
mCoinCountText.setText("Coins: " + mCoinCount);
}
private void startGame() {
// Hide the retry button, load the ad, and start the timer.
mRetryButton.setVisibility(View.INVISIBLE);
mShowVideoButton.setVisibility(View.VISIBLE);
loadRewardedVideoAd();
createTimer(COUNTER_TIME);
mGamePaused = false;
mGameOver = false;
}
// Create the game timer, which counts down to the end of the level
// and shows the "retry" button.
private void createTimer(long time) {
final TextView textView = ((TextView) findViewById(R.id.timer));
if (mCountDownTimer != null) {
mCountDownTimer.cancel();
}
mCountDownTimer = new CountDownTimer(time * 1000, 50) {
#Override
public void onTick(long millisUnitFinished) {
mTimeRemaining = ((millisUnitFinished / 1000) + 1);
textView.setText("seconds remaining: " + mTimeRemaining);
}
#Override
public void onFinish() {
if (mRewardedVideoAd.isLoaded()) {
mShowVideoButton.setVisibility(View.VISIBLE);
}
textView.setText("You Lose!");
addCoins(GAME_OVER_REWARD);
mRetryButton.setVisibility(View.VISIBLE);
mGameOver = true;
}
};
mCountDownTimer.start();
}
private void showRewardedVideo() {
mShowVideoButton.setVisibility(View.INVISIBLE);
if (mRewardedVideoAd.isLoaded()) {
mRewardedVideoAd.show();
}
}
#Override
public void onRewardedVideoAdLeftApplication() {
Toast.makeText(this, "onRewardedVideoAdLeftApplication", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdClosed() {
Toast.makeText(this, "onRewardedVideoAdClosed", Toast.LENGTH_SHORT).show();
// Preload the next video ad.
loadRewardedVideoAd();
}
#Override
public void onRewardedVideoAdFailedToLoad(int errorCode) {
Toast.makeText(this, "onRewardedVideoAdFailedToLoad", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdLoaded() {
Toast.makeText(this, "onRewardedVideoAdLoaded", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewardedVideoAdOpened() {
Toast.makeText(this, "onRewardedVideoAdOpened", Toast.LENGTH_SHORT).show();
}
#Override
public void onRewarded(RewardItem reward) {
Toast.makeText(this,
String.format(" onRewarded! currency: %s amount: %d", reward.getType(),
reward.getAmount()),
Toast.LENGTH_SHORT).show();
addCoins(reward.getAmount());
}
#Override
public void onRewardedVideoStarted() {
Toast.makeText(this, "onRewardedVideoStarted", Toast.LENGTH_SHORT).show();
}
I am using my Ad_Unit_ID Live not tested Device ID