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
Related
I'm trying to do admost interstitial integration into my application. There are tab actions in my application, so there is bottom navigation at the bottom of the screen, and when they are clicked, interstitial should appear, at least I think I coded it that way, but it never loads because interstitial.isLoaded is null. interstitial does not come null activity , does not come null , but isLoaded does not show at all because it is always false . I'm sharing my codes can you help me with this I'm stuck here
I only share the necessary stuff because I have set up an abstract factory structure and it would be too complicated to share the whole structure
public void ifNeededShowinterstitial(){
if(UserConfig.enabledAds && UserConfig.enabledInterstitialAds){
DYTIntersitialProvider interstitial = DYTBannerFactory.shared().interstitial(DYTBannerFactory.shared().getBannerIdContainer().interstitial());
if(interstitial instanceof DYTBannerActivityClient){
((DYTBannerActivityClient) interstitial).setActivity(BaseActivity.mainActivity);
}
interstitial.load();
}
}
public void gotoExerciseActivity() {
behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
Intent i = new Intent(MainActivity.this, ExerciseActivity.class);
i.addFlags(Intent.FLAG_FROM_BACKGROUND);
startActivity(i);
//overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
ifNeededShowinterstitial();
}
For example, in this code, when the exercise button on the navigation bar is clicked, it calls the ifNeededShowinterstitial function at the bottom, which calls load.
AdMostInterstitial interstitial;
Activity activity;
#Override
public void setActivity(Activity activity) {
this.activity = activity;
}
#Override
public void load() {
if (interstitial == null) {
AdMostAdListener listener = new AdMostAdListener() {
#Override
public void onDismiss(String message) {
Log.d(Statics.TAG, "MainActivity interstitial onDismiss network: " + message);
}
#Override
public void onComplete(String s) {
Log.d(Statics.TAG, "MainActivity interstitial onComplete network: " + s);
}
#Override
public void onFail(int errorCode) {
logError(errorCode, "interstitial");
}
#Override
public void onReady(String network, int ecpm) {
Log.d(Statics.TAG, "MainActivity interstitial onReady network : " + network);
}
#Override
public void onShown(String network) {
Log.d(Statics.TAG, "MainActivity interstitial onShown network: " + network);
}
#Override
public void onClicked(String s) {
Log.d(Statics.TAG, "MainActivity interstitial onClicked network: " + s);
}
#Override
public void onStatusChanged(int i) {
}
};
interstitial = new AdMostInterstitial(this.activity, Statics.FULLSCREEN_ZONE, listener);
}
interstitial.refreshAd(false);
if(interstitial != null && interstitial.isLoaded())
interstitial.show();
}
Every time these navigation buttons are clicked, load is called and these codes work. I did the same codes in the documentation codes. What could be the problem? Is there something missing or am I doing something wrong I couldn't figure it out please help?
you can see it here in the documentation: https://admost.github.io/amrandroid/
I have a fragment that contains a listview , I want to show interstial ad whene the user click a listview item , I tried the following code but it is not showing :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
......
mInterstitialAd = new InterstitialAd(mContext);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
}
});
......
return rootView;
}
Set up new class which have set, load and show interstatialAd static methods as below:
public class AdSetup {
// Application context returned by function --> Application.get()
public static String TesttingDeviceID = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
final static InterstitialAd mInterstitialAd = new InterstitialAd(Application.get());
public static void setInterstitial() {
try {
if (mInterstitialAd.getAdUnitId() == null) {
mInterstitialAd.setAdUnitId(Application.get().getString(R.string.interstitialAd));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void loadInterstatial() {
try {
setInterstitial();
AdRequest adRequestInter = new AdRequest.Builder().build();
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
Log.e("mInterstetial onloaded", "onloaded isLoaded" + mInterstitialAd.isLoaded());
}
#Override
public void onAdFailedToLoad(int i) {
Log.e("mInterstetial onloaded", "onloaded onAdFailedToLoad");
}
#Override
public void onAdOpened() {
// super.onAdOpened();
}
#Override
public void onAdClosed() {
// super.onAdClosed();
}
#Override
public void onAdClicked() {
// super.onAdClicked();
}
});
mInterstitialAd.loadAd(adRequestInter);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void showInterstatial() {
try {
Log.e("mInterstetial show ", "isLoaded" + mInterstitialAd.isLoaded());
if (mInterstitialAd.isLoaded() && mInterstitialAd.getAdUnitId() != null) {
mInterstitialAd.show();
} else {
loadInterstatial();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
How to call this methods on click of the list item or the onCreate() of the new Activity to comply with the interstatial ad policy:
AdSetup.showInterstatial(); // Show ad if already loaded else load Ad
AdSetup.loadInterstatial(); // Load new ad
Make sure to follow the policies listed in the below links:
Disallowed interstitial implementations
App load or exit Do not place interstitial ads on app load and when
exiting apps as interstitials should only be placed in between pages
of app content. Ads should not be placed in applications that are
running in the background of the device or outside of the app
environment. It should be clear to the user which application the ad
is associated with or implemented on.
Recommended interstitial implementations
Also, add Application class:
public class Application extends android.app.Application {
// public static DeviceName.DeviceInfo deviceInfo;
private static Application _instance;
#Override
public void onCreate() {
super.onCreate();
_instance = this;
}
//return the App context
public static Application get() {
return _instance;
}
}
Also declare the Application class in your AndroidManifest.xml as you can see below first line:
<application
android:name=".Application"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:allowBackup="false"
android:supportsRtl="true"
android:networkSecurityConfig="#xml/network_security_config"
android:theme="#style/AppTheme">
I just implemented this in my code. It works. In the example that you gave I did not see if you implemented AdListener after AdRequest.Builder. If not, here is an example of that:
ExampleInterstitial.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
ExampleInterstitial.loadAd(new AdRequest.Builder().build());
}
});
Next, it appeared in your example that you just have the interstitial ad to show onItemClick but do you have an intent to move to a new activity also set there? I didn't see it. Check out my code below. I set the intent to start the new activity then I show the add after. Just a thought because this works for me. Good luck!
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent;
intent = new Intent(getActivity(), ExampleActivity.class);
startActivity(intent);
if (ExampleInterstitial.isLoaded()) {
ExampleInterstitial.show();
}
else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
}
});
Anybody know how to show the interstitial ads when the user click the button second time.I mean when the user click the button once then the ad should not appear but whenever the user click the same button second time then the ad must show..
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
ShowInterstitial showInterstitial;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showInterstitial = new ShowInterstitial(this);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.app_bar);
/*toolbar = findViewById(R.id.app_bar);
toolbar.setTitle("hell");
toolbar.*/
}
int counter = 0;
public void onClick(View view) {
if(view.getId() == R.id.ll1 ) {
counter++;
if (counter == 2) {
counter = 0;
Intent intent = new Intent(this, AggregatesActivity.class);
startActivity(intent);
if (showInterstitial != null && ShowInterstitial.isLoaded())
showInterstitial.showInterstitial();
}
}
and ShowInterstitial code is here which i calling in different activities.
public class ShowInterstitial {
private InterstitialAd mInterstitialAd;
private Context context;
private boolean isAddReplace = false;
public ShowInterstitial(Context context) {
this.context = context;
mInterstitialAd = newInterstitialAd(context);
loadInterstitial();
}
private InterstitialAd newInterstitialAd(final Context context) {
InterstitialAd interstitialAd = new InterstitialAd(context);
/*if (!isAddReplace)
interstitialAd.setAdUnitId(context.getString(R.string.interstitial_one));*/
interstitialAd.setAdUnitId(context.getString(R.string.interstitial_one));
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
isAddReplace = !isAddReplace;
}
#Override
public void onAdFailedToLoad(int errorCode) {
}
#Override
public void onAdClosed() {
goToNextLevel();
}
});
return interstitialAd;
}
public boolean showInterstitial() {
if (mInterstitialAd != null && mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
goToNextLevel();
}
return false;
}
public void loadInterstitial() {
// Disable the next level button and load the ad.
AdRequest adRequest = new AdRequest.Builder()
.setRequestAgent("android_studio:ad_template").build();
mInterstitialAd.loadAd(adRequest);
}
private void goToNextLevel() {
// Show the next level and reload the ad to prepare for the level after.
mInterstitialAd = newInterstitialAd(context);
loadInterstitial();
}
}
#Sufyan Hashmi you need a int variable whose value will increase on every click whenever the value is 2 you should call load inerestitial ad and assign the variable's value zero.
int counter = 0;
if(view.getId()==R.id.ll1)
{
counter++;
if (counter == 2) {
counter = 0;
Intent intent = new Intent(this, AggregatesActivity.class);
startActivity(intent);
if (showInterstitial != null && showInterstitial.isLoaded())
showInterstitial.showInterstitial();
}
}
How to show the interstitial ads on second click in android?
You can take boolean variable and manage click event based on that boolean variable
Example : take a boolean variable with true value
Than inside ClickListener when user clicks the button check that boolean variable is true means use clicked first time the button
and change the value of boolean variable to false
SAMPLE CODE
take one boolean variable
boolean isFirstTimeClick=true;
Now make your ClickListener like this
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(isFirstTimeClick){
isFirstTimeClick=false;
Toast.makeText(PicturePreviewActivity.this, "First Time Click", Toast.LENGTH_SHORT).show();
}else {
isFirstTimeClick=true;
Toast.makeText(PicturePreviewActivity.this, "Second Time Click", Toast.LENGTH_SHORT).show();
}
}
});
I'm new to InMobi and I'm trying to implement a banner ad to my app.
Here's my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpBannerAd();
}
private void setUpBannerAd(){
InMobiSdk.init(MainActivity.this, MY_ID);
InMobiBanner bannerAd = findViewById(R.id.banner);
bannerAd = new InMobiBanner(MainActivity.this, BANNER_ID);
bannerAd.setListener(new InMobiBanner.BannerAdListener() {
#Override
public void onAdLoadSucceeded(InMobiBanner inMobiBanner) {
Toast.makeText(MainActivity.this, "sucess", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdLoadFailed(InMobiBanner inMobiBanner,
InMobiAdRequestStatus inMobiAdRequestStatus) {
Toast.makeText(MainActivity.this, "fail", Toast.LENGTH_SHORT).show();
}
#Override
public void onAdDisplayed(InMobiBanner inMobiBanner) {
}
#Override
public void onAdDismissed(InMobiBanner inMobiBanner) {
}
#Override
public void onAdInteraction(InMobiBanner inMobiBanner, Map<Object, Object> map) {
}
#Override
public void onUserLeftApplication(InMobiBanner inMobiBanner) {
}
#Override
public void onAdRewardActionCompleted(InMobiBanner inMobiBanner, Map<Object, Object> map) {
}
});
bannerAd.load();
}
}
I think i have all the needed imports as well as manifest declarations, but not entirely sure because I'm new to the platform. Test ads are turned on. Toasts do NOT even show up.
Thanks for replies!
You need to add the banner to the view hierarchy once its created. Something like this:
RelativeLayout adContainer = (RelativeLayout) findViewById(R.id.ad_container);
RelativeLayout.LayoutParams bannerLp = new
RelativeLayout.LayoutParams(640, 100);
bannerLp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
bannerLp.addRule(RelativeLayout.CENTER_HORIZONTAL);
adContainer.addView(bannerAd, bannerLayoutParams);</code>
It looks like you created the banner twice. Once in XML, and once in code:
//the banner is created below by reference to xml
InMobiBanner bannerAd = findViewById(R.id.banner);
//the banner is created below in code
bannerAd = new InMobiBanner(MainActivity.this, BANNER_ID);</code>
Check out this guide for more details: https://support.inmobi.com/monetize/android-guidelines/banner-ads-for-android/
I am trying to add interstitial ads to my game. It is built on a framework from a book. The constructor is:
public GameScreen(Game game) {
super(game);
world = new World();
clueLetters = new String[10];
levelNo = SettingsObject.levelUnlock;
getWord();
interstitialAd = new InterstitialAd(AndroidGame.context);
interstitialAd.setAdUnitId("ca-app-pub-1861496496821617/");
//Create an ad request
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
AndroidGame.activityReference.runOnUiThread(new Runnable() {
#Override
public void run()
{
// Set AdListener
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
super.onAdClosed();
}
});
}
});
Looper.prepare();
interstitialAd.loadAd(adRequestBuilder.build());
}
However, I get the error:
java.lang.IllegalStateException: setAdListener must be called on the main UI thread.
Can you tell me why I am getting that error and how to fix it, please?
I use the a similar/same framework. The best way is to set up the interstitial ads in the AndroidGame activity class and use an interface to show the ads in your game screen:
First create the interface class:
public interface MyActivityListener {
public void showInterstitial();
}
Then in your AndroidGame class, implement the interface:
public abstract class AndroidGame extends Activity implements Game, MyActivityListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
interstitialAd = new InterstitialAd(AndroidGame.context);
interstitialAd.setAdUnitId("ca-app-pub-1861496496821617/");
//Create an ad request
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
interstitialAd.loadAd(adRequestBuilder.build());
// Set AdListener
interstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
super.onAdClosed();
}
});
}
#Override
public void showInterstitial() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if(interstitialAd != null && interstitialAd.isLoaded())
interstitialAd.show();
}
});
}
}
With this, any time you want to show ads in any screen, you just get call the showInterstitial() method. Example in your game screen:
public class GameScreen extends Screen{
MYActivityListener mL;
public GameScreen(Game game) {
super(game);
mL = (MyActivityListener)game;
world = new World();
clueLetters = new String[10];
levelNo = SettingsObject.levelUnlock;
getWord();
mL.showInterstitial();
}
}
I use this implementation to do all work that requires running on the UI thread (hide and show banner ads, rate/share app, storing scores etc. Hope it helps :)