How to refresh native ads in specific time using Admob? - android

I'm working in my Android application and i integrated native ads from Google Admob and it works well as shown in the picture below. But my problem is i want it refresh itself automatically. And this is my code used to refresh the ad. Any ideas? Thanks.
private void refreshAd() {
AdLoader.Builder builder = new AdLoader.Builder(this, ADMOB_AD_UNIT_ID);
builder.forUnifiedNativeAd(new UnifiedNativeAd.OnUnifiedNativeAdLoadedListener() {
// OnUnifiedNativeAdLoadedListener implementation.
#Override
public void onUnifiedNativeAdLoaded(UnifiedNativeAd unifiedNativeAd) {
// You must call destroy on old ads when you are done with them,
// otherwise you will have a memory leak.
if (nativeAd != null) {
nativeAd.destroy();
}
nativeAd = unifiedNativeAd;
FrameLayout frameLayout =
findViewById(R.id.fl_adplaceholder);
UnifiedNativeAdView adView = (UnifiedNativeAdView) getLayoutInflater()
.inflate(R.layout.activity_ads, null);
populateUnifiedNativeAdView(unifiedNativeAd, adView);
frameLayout.removeAllViews();
frameLayout.addView(adView);
}
});
NativeAdOptions adOptions = new NativeAdOptions.Builder()
.build();
builder.withNativeAdOptions(adOptions);
AdLoader adLoader = builder.withAdListener(new AdListener() {
#Override
public void onAdFailedToLoad(int errorCode) {
Toast.makeText(MainActivity.this, "Failed to load native ad: "
+ errorCode, Toast.LENGTH_SHORT).show();
}
}).build();
adLoader.loadAd(new AdRequest.Builder().build());
}

Related

Admob interstitial ad latency issues when loading ad

I am trying to implement interstitial ad in a fragment, when button is clicked the fragment doesn't open other activity , but loads data in same fragment so i can't use the they way people say interstisial ad should be used when navigating between activities. instead i am using the ad for only once when button is clicked .it works but takes sometime .how to deal with it?
it only works if user pressed the button after few seconds of launching the app.
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
root = inflater.inflate(R.layout.fragment_home, container, false);
Button btn=root.findViewById(R.id.btn);
initAds();
btn.setOnClickListener(this);
return root;
}
#Override
public void onClick(View view){
initAdsCallBack();
}
private void initAds(){
MobileAds.initialize(requireActivity(), new OnInitializationCompleteListener() {
#Override
public void onInitializationComplete(#NonNull InitializationStatus initializationStatus) {
createNonPersonalisedAd();
}
});
}
}
private void createNonPersonalisedAd() {
Bundle networkExtrasBundle = new Bundle();
networkExtrasBundle.putInt("rdp", 1);
AdManagerAdRequest adRequest = (AdManagerAdRequest) new AdManagerAdRequest.Builder()
.addNetworkExtrasBundle(AdMobAdapter.class, networkExtrasBundle)
.build();
createInterstitialAd(adRequest);
}
private void createInterstitialAd(AdRequest adRequest){
AdManagerInterstitialAd.load(requireActivity(),getResources().getString(R.string.str_iterstitial), (AdManagerAdRequest) adRequest,
new AdManagerInterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull AdManagerInterstitialAd interstitialAd) {
// The mAdManagerInterstitialAd reference will be null until
// an ad is loaded.
mAdManagerInterstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
///// best place to callback is here coz its successfully loaded here
mAdManagerInterstitialAd.setFullScreenContentCallback(new FullScreenContentCallback(){
#Override
public void onAdDismissedFullScreenContent() {
// Called when fullscreen content is dismissed.
Log.d("TAG", "The ad was dismissed.");
createInterstitialAd(adRequest);
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when fullscreen content failed to show.
Log.d("TAG", "The ad failed to show.");
}
#Override
public void onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
// Make sure to set your reference to null so you don't
// show it a second time.
mAdManagerInterstitialAd = null;
Log.d("TAG", "The ad was shown.");
}
});
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
Log.i(TAG, loadAdError.getMessage());
mAdManagerInterstitialAd = null;
}
});
}
private void initAdsCallBack(){
if (mAdManagerInterstitialAd != null) {
mAdManagerInterstitialAd.show(requireActivity());
debugToast("ad shown");
} else {
Log.e("Tad didn't show");
}
}
Consider pre-loading your interstitial ads to reduce latency when displaying them to your users. For more information about pre-loading your interstitial ads refer to the AdMob Interstitial Ad developer guidelines for apps developed for Android

i am using anjlab library for in app billing but " bp.loadOwnedPurchasesFromGoogle() " always returning false

Here bp.loadOwnedPurchasesFromGoogle() is always returning false so the code is not getting executed and ads are showing even if the purchase is madde
Here is the link to anjlab billing library documentation:
https://github.com/anjlab/android-inapp-billing-v3
I have tried the following code .The method restore() is being called inside the onCreate().
public void restore(){
if (bp.loadOwnedPurchasesFromGoogle()){
if (bp.isPurchased("remove_ads")){
FancyToast.makeText(MainActivity.this,"Pro Version Restored",FancyToast.LENGTH_LONG,FancyToast.INFO,true).show();
CoordinatorLayout adscontainer = (CoordinatorLayout) findViewById(R.id.coordinator);
View admobAds = (View) findViewById(R.id.adView);
adscontainer.removeView(admobAds);
}
else
{
MobileAds.initialize(this,"ca-app-pub-8443413787087664~2607463808");
mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
loadInterstitialAd();
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
Log.i("hello","world");
runOnUiThread(new Runnable() {
#Override
public void run() {
if (mInterstitialAd.isLoaded()){
mInterstitialAd.show();
}
else {
Log.d("TAG","Interstitial Ad not loaded");
}
loadInterstitialAd();
}
});
}
},30,30, TimeUnit.SECONDS);
}
}
}
The ads shouldnt get loaded if the user has purchased pro product.

Unable to display ads ErrorCode: 0 in ads android

I integrate google admob ads but it's displaying an error as,
W/Ads: There was a problem getting an ad response. ErrorCode: 0
08-09 16:05:43.933 24002-24002/com.locationtracking W/Ads: Failed to load ad: 0
I created a new ad id and copied the interstital ad unit id and app id but it's not working.
But when I used testing interstial id, it's displaying an ad. But when i copy and use the interstital id created, it's not displaying the ads. For past few days, I am struggling in this. I created new account and checked. Still same error.
MobileAds.initialize(this, "ca-app-pub-9172823052987868~3234462570");
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-9172823052987868/8576265071");
AdRequest adRequestInterstitial = new AdRequest.Builder().addTestDevice("deviceid").build();
mInterstitialAd.loadAd(adRequestInterstitial);
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
}
#Override
public void onAdLoaded() {
mAdIsLoading = false;
showInterstitial();
}
#Override
public void onAdFailedToLoad(int errorCode) {
mAdIsLoading = false;
}
});
}
private void showInterstitial() {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
AdRequest adRequest = new AdRequest.Builder().addTestDevice("deviceid").build();
mInterstitialAd.loadAd(adRequest);
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.google.android.gms:play-services-ads:9.2.1'
compile 'com.google.android.gms:play-services-analytics:9.2.1'
}
Common Error! There is no fault in your code. It's all good.
You just need to wait a little. Your ad id is newly created so it will take some time to fetch ads from google servers. You can verify this by adding banner/interstitial ad id you creating for earlier applications and you'll see that they work. So give it some time and it will work soon. At least for me, it happens all the time.
W/Ads: There was a problem getting an ad response. ErrorCode: 0 08-09 16:05:43.933 24002-24002/com.locationtracking W/Ads: Failed to load ad: 0
remove addTestDevice("deviceid"); from your code display real ads
AdRequest adRequestInterstitial = new AdRequest.Builder().addTestDevice("deviceid").build();
to
AdRequest adRequestInterstitial = new AdRequest.Builder().build();
try bellow code its running well:
public class MainActivity extends AppCompatActivity {
InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
////////////////////////// banner/////////////////////////
AdView mAdView = (AdView) findViewById(R.id.adView);
//AdRequest adRequest = new AdRequest.Builder().addTestDevice("7339C0A9091FA2D6AA9A2BF29077B5EA").build();
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
///////////////////////////////////////////////////////////
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(getResources().getString(R.string.interstitial_unit_id));
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
loadAdd();
}
});
loadAdd();
}
#Override
protected void onStart() {
super.onStart();
showInterstitial();
}
#Override
protected void onStop() {
super.onStop();
showInterstitial();
}
//////////////////////////////////add Interstitial section//////////////////////////////////////////////
private void showInterstitial() {
// Show the ad if it's ready. Otherwise toast and restart the game.
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
//Toast.makeText(this, "Ad did not load", Toast.LENGTH_SHORT).show();
loadAdd();
}
}
private void loadAdd() {
// Request a new ad if one isn't already loaded, hide the button, and kick off the timer.
if (!mInterstitialAd.isLoading() && !mInterstitialAd.isLoaded()) {
//AdRequest adRequest = new AdRequest.Builder().addTestDevice("7339C0A9091FA2D6AA9A2BF29077B5EA").build();
AdRequest adRequest = new AdRequest.Builder().build();
mInterstitialAd.loadAd(adRequest);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
compile 'com.google.android.gms:play-services-ads:8.3.0'
You can not display real ad in the test device, so you should remove the test device code when you upload your apk=> change your code as this
AdRequest adRequestInterstitial = new AdRequest.Builder().build();

Interstitial Ad not showing (with Banner ads)

I tried to add the code as per Google ADMOB Ads but it didn't work. Then I started working with GITHUB example to add Interstitial ads. I have no errors whatsoever in my project. Eclipse shows nothing in place of ads. Please have a look at my code and tell me where am I going wrong. I will highlight stuff wherever necessary. BANNER ADS ARE WORKING!!!!
public class AppGame extends Activity {
AdView adView;
/** The log tag. */
private static final String LOG_TAG = "InterstitialSample";
/** Your ad unit id. Replace with your actual ad unit id. */
private static final String AD_UNIT_ID1 = "INSERT AD ID HERE";
/** The interstitial ad. */
private InterstitialAd interstitialAd;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
interstitialAd = new InterstitialAd(this);
interstitialAd.setAdUnitId(AD_UNIT_ID1);
// Set the AdListener.
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
Log.d(LOG_TAG, "onAdLoaded");
}
#Override
public void onAdFailedToLoad(int errorCode) {
// Change the button text and disable the button.
}
});
}
/** Called when the Load Interstitial button is clicked. */
public void loadInterstitial(View unusedView) {
// Disable the show button until the new ad is loaded.
// Check the logcat output for your hashed device ID to get test ads on a physical device.
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("INSERT_YOUR_HASHED_DEVICE_ID_HERE")
.build();
// Load the interstitial ad.
interstitialAd.loadAd(adRequest);
}
/** Called when the Show Interstitial button is clicked. */
public void showInterstitial(View unusedView) {
// Disable the show button until another interstitial is loaded.
if (interstitialAd.isLoaded()) {
interstitialAd.show();
} else {
Log.d(LOG_TAG, "Interstitial ad was not ready to be shown.");
}
}
/** Gets a string error reason from an error code. */
private String getErrorReason(int errorCode) {
String errorReason = "";
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;
}
}
Call loadInterstitial(v) after setting setting the adunit:
interstitialAd.setAdUnitId(AD_UNIT_ID1);
loadInterstitial(v);
And call showInterstitial(v) when/where you want to show the ad:
You forgot to call the loadInterstitial function for the interstitial ad to load.
In your onCreate function, call the loadInterstitial function. Then add the listener to it like so:
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
Log.d(LOG_TAG, "onAdLoaded");
interstitialAd.show();
}
or set a boolean to true and at a natural breakpoint in your app, check if the boolean is true and then show the ad.
I have the same problem in my one of the testing device. I searched so many days. But i didn't get any solution.
At last I tried by removing the code
.addTestDevice("INSERT_YOUR_HASHED_DEVICE_ID_HERE")
and I got successful result.
So try like this at last step of testing.
onCreate add below lines
mInterstitialAd = new InterstitialAd(this);
// set the ad unit ID
mInterstitialAd.setAdUnitId(getString(R.string.interstitial_full_screen));
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
}
#Override
public void onAdLoaded() {
// Ads loaded, stop requesting
mInterstitialAd.show();
//update time start
timeStart = new Date().getTime();
}
});
onResume check time show Intertitial Ads and send request Ads:
if(new Date().getTime()-timeStart>=timeShowAds) {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("36E0B62FE34536712ED1BEBD85467085")
.build();
// Load ads into Interstitial Ads
mInterstitialAd.loadAd(adRequest);
}

How to integrate admob banner into Android app

How to integrate admob into my Android app?
I have use this link: google code
but I think there are not all the information needed.
I'm not too certain about the tutorial, as I just worked through the API to get it to work. Here's my code:
AdView adView = new AdView(OOKL.this, AdSize.BANNER, MY_AD_UNIT_ID);
LinearLayout al = (LinearLayout) findViewById(R.id.AdLayout);
al.addView(adView, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
adReq = new AdRequest();
adReq.setTesting(IS_DEBUG);
adView.loadAd(adReq);
adView.setAdListener(new AdListener() {
public void onReceiveAd(Ad ad) {
setAdVisible(true);
}
public void onFailedToReceiveAd(Ad ad, AdRequest.ErrorCode error) {
setAdVisible(false);
}
public void onPresentScreen(Ad ad) {
}
public void onDismissScreen(Ad ad) {
}
public void onLeaveApplication(Ad ad) {
}
});
private void setAdVisible(boolean show) {
View v = this.findViewById(R.id.AdLayout);
v.setVisibility(show ? View.VISIBLE : View.GONE);
}
This is pretty much all you need. Here IS_DEBUG is my private variable controlling whether I'm running in test mode or live production. MY_AD_UNIT_ID is the ad unit ID you get when you register the app with AdMob. AdLayout is a LinearLayout that would contain the AdView - it's the first child in a vertical LinearLayout.

Categories

Resources