Как показывать межстраничную рекламу при нажатии кнопки «Назад» Android

Хай друзья! Мне нужна помощь от вас, ребята, относительно моего приложения для Android. В основном мой проект Android представляет собой вкладку фрагмента, где я хочу показывать межстраничную рекламу, когда пользователь нажимает кнопку «Назад» перед закрытием приложения.

Пожалуйста, проверьте мой код ниже и помогите мне разобраться с этим вопросом как можно быстрее, спасибо :)

MainActivity.java

public class MainActivity extends AppCompatActivity {



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);



    TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/01"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/02"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/03"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/04"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/05"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/06"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/07"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/08"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/09"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/10"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/11"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/12"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/13"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/14"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/15"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/16"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/17"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/18"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/19"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/20"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/21"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/22"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/23"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/24"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/25"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/26"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/27"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/28"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/29"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/30"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/31"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/32"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/33"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/34"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/35"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/36"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/37"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/38"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/39"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/40"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/41"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/42"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/43"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/44"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/45"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/46"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/47"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/48"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/49"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/50"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/51"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/52"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/53"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/54"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/55"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/56"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/57"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/58"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/59"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/60"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/61"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/62"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/63"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/64"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/65"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/66"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/67"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/68"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/69"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/70"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/71"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/72"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/73"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/74"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/75"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/76"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/77"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/78"));
    tabLayout.addTab(tabLayout.newTab().setText("Ashaar/79"));


    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);


    final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
    final PagerAdapter adapter = new PagerAdapter
            (getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(adapter);
    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }


    });
}





@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}



public void onBackPressed() {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            MainActivity.this);

    // set title
    alertDialogBuilder.setTitle("Exit");

    // set dialog message
    alertDialogBuilder
            .setMessage("Do you really want to exit?")
            .setCancelable(false)
            .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    // if this button is clicked, close
                    // current activity
                    MainActivity.this.finish();
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.cancel();
                }
            });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
}

public void sharevia(MenuItem item) {
    Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
    sharingIntent.setType("text/plain");
    String shareBody = "https://play.google.com/store/apps/details?id=com.islamichub.dil.jalay";
    sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "https://play.google.com/store/apps/details?id=com.islamichub.dil.jalay");
    sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
    startActivity(Intent.createChooser(sharingIntent, "Share via"));
}

public void rating(MenuItem item) {
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.islamichub.dil.jalay")));
}

public void findmore(MenuItem item) {
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pub:IslamicHub")));
}

public void aboutme(MenuItem item) {
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.fb.com/topitideas")));
}

activity_main.xml

<RelativeLayout
android:id="@+id/main_layout"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
tools:context=".MainActivity">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="?attr/colorPrimary"
    android:elevation="6dp"
    app:titleTextColor="#ffffff"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

<android.support.design.widget.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/toolbar"
    android:background="?attr/colorPrimaryDark"
    android:elevation="6dp"
    app:tabSelectedTextColor="#ffff00"
    app:tabTextColor="#000000"
    android:minHeight="?attr/actionBarSize"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:tabMode="scrollable"/>

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:layout_below="@id/tab_layout" />


person Saeed Rehman    schedule 17.02.2017    source источник


Ответы (2)


Загрузите экземпляр объявления в метод onCreate(). Таким образом, вы можете предварительно выбрать объявление без загрузки. И запиши как..

@Override
public void onBackPressed() {
    showAdvertisement();
}

private void showAdvertisement() {
    if (mInterstitialAd.isLoaded()) {
        mInterstitialAd.show();
    } else {
        finish();
    }
}

private void loadInterstitialAd() {
    AdRequest adRequest = new AdRequest.Builder()
            .build();

    mInterstitialAd.loadAd(adRequest);
}
person Meenu Meena    schedule 17.02.2017
comment
mInterstitialAd = новое межстраничное объявление (это); mInterstitialAd.setAdUnitId(************); mInterstitialAd.setAdListener(new AdListener() { @Override public void onAdClosed() { finish(); } }); загрузить межстраничную рекламу(); - person Meenu Meena; 20.02.2017
comment
Сделайте то же самое в методе onCreate(). Чтобы создать межстраничную рекламу, вам нужно пройти документ Google Admob. - person Meenu Meena; 20.02.2017

Я предполагаю, что вы находитесь в основной активности, и в стеке нет никакой активности. Вам нужно переопределить метод onBackPressed() и добавить код для промежуточного добавления в onBackPressed()

@Override
public void onBackPressed() {
//Interstitial code goes here
}

Для добавления межстраничного кода или справки по коду перейдите по ссылке ниже https://firebase.google.com/docs/admob/android/interstitial

person Abdul Waheed    schedule 17.02.2017