在Android studio中添加横幅广告Admob

moiiocjp  于 2023-02-14  发布在  Android
关注(0)|答案(3)|浏览(156)

请帮助我。当我将admob添加到我的程序中时,此代码不起作用。可能是我用错了方法。请建议我编辑带有横幅广告admob的代码。我应该在哪里添加admob代码?调试中没有错误,但应用程序未运行无法加载应用程序。谢谢。

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

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open,    R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        mYoutubeDataApi = new YouTube.Builder(mTransport, mJsonFactory, null)
                .setApplicationName(getResources().getString(R.string.app_name))
                .build();

        youtubePlaylist = getString(R.string.playlist_1);
        token = null;
        listVideoInfo = null;
        listViewVideo = (ListView) findViewById(R.id.list_view_video);
        listViewVideo.setOnItemClickListener(onItemClickListener);

        setTitle(getIntent().getStringExtra("USER_NAME"));
        loadPlayList();

        mAdView = (AdView) findViewById(R.id.ad_view);
        AdRequest adRequest = new AdRequest.Builder()
                .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                .addTestDevice("55DBCB068B472972E7ABC20D047D27E4")// Add your real device id here
                .build();
        // Start loading the ad in the background.
        mAdView.loadAd(adRequest);
    }

    /**
     * Called when leaving the activity
     */
    @Override
    public void onPause() {
        if (mAdView != null) {
            mAdView.pause();
        }
        super.onPause();
    }

    /**
     * Called when returning to the activity
     */
    @Override
    public void onResume() {
        super.onResume();
        if (mAdView != null) {
            mAdView.resume();
        }
    }

    /**
     * Called before the activity is destroyed
     */
    @Override
    public void onDestroy() {
        if (mAdView != null) {
            mAdView.destroy();
        }
        super.onDestroy();
    }
    

    private void loadPlayList(){
        new GetPlaylistAsyncTask(mYoutubeDataApi, getApplicationContext()) {
            int numbersPage;
            @Override
            protected void onProgressUpdate(final Integer... values) {
                super.onProgressUpdate(values);
                numbersPage = values[0] / 10;
            }

            @Override
            public void onPostExecute(Pair<String, List<VideoInfo>> result) {
                token=result.first;
                if(listVideoInfo ==null) {
                    listVideoInfo = result.second;
                    adapterVideo=new AdapterVideo(getApplicationContext(), listVideoInfo);
                    listViewVideo.setAdapter(adapterVideo);
                    listViewVideo.setOnScrollListener(new InfiniteScrollListener(1,numbersPage) {
                        @Override
                        public void onReloadItems(int pageToRequest) {
                            loadPlayList();
                        }

                        @Override
                        public void onReloadFinished() {

                        }
                    });
                }
                else {
                    listVideoInfo.addAll(result.second);
                    adapterVideo.notifyDataSetChanged();
                }
            }
        }.execute(youtubePlaylist, token);
    }

    AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,  long id) {
            Intent intent = new Intent(getApplicationContext(),      YtbActivity.class);
            intent.putExtra("VIDEO_ID", listVideoInfo.get(position).getId());
            startActivity(intent);
        }
    };

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.pl_list1) {
            youtubePlaylist = getString(R.string.playlist_1);
            listVideoInfo =null;
            token=null;
            loadPlayList();
        } else if (id == R.id.pl_list2) {
            youtubePlaylist = getString(R.string.playlist_2);
            listVideoInfo =null;
            token=null;
            loadPlayList();
        } else if (id == R.id.pl_list3) {
            youtubePlaylist = getString(R.string.playlist_3);
            listVideoInfo =null;
            token=null;
            loadPlayList();
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
   }

Activity_main.xml

<android.support.design.widget.CoordinatorLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context=".MainActivity">
    
        <RelativeLayout
            android:id="@+id/main_content"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
    
            <android.support.design.widget.CoordinatorLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_above="@+id/ad_view">
    
                <android.support.design.widget.AppBarLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:theme="@style/AppTheme.AppBarOverlay">
    
                    <android.support.v7.widget.Toolbar
                        android:id="@+id/toolbar"
                        android:layout_width="match_parent"
                        android:layout_height="?attr/actionBarSize"
                        android:background="?attr/colorPrimary"
                        app:layout_scrollFlags="scroll|enterAlways"
                        app:popupTheme="@style/AppTheme.PopupOverlay" />
    
    
                </android.support.design.widget.AppBarLayout>
    
                <ListView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:id="@+id/list_view_video">
    
                </ListView>
    
            </android.support.design.widget.CoordinatorLayout>
    
            <com.google.android.gms.ads.AdView
                android:id="@+id/ad_view"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_alignParentBottom="true"
                ads:adSize="BANNER"
                ads:adUnitId="ca-app-pub-3940256099942544/6300978111">
            </com.google.android.gms.ads.AdView>
    
        </RelativeLayout>
        </android.support.design.widget.CoordinatorLayout>
mzillmmw

mzillmmw1#

你只需要在你的活动中有这样的东西:

AdView adView = (AdView)findViewById(R.id.adView);
 AdRequest adRequest = new AdRequest.Builder().build();
 adView.loadAd(adRequest);

包含您添加的视图:

<RelativeLayout> 
 ...
    <com.google.android.gms.ads.AdView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        ads:adSize="BANNER"
        ads:adUnitId="@string/banner_ad_unit_id"
        android:id="@+id/adView">
    </com.google.android.gms.ads.AdView>

</RelativeLayout>

您的AndroidManifest.xml中的广告活动:

<activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent"/>

不要忘记AndroidManifest.xml中的权限:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

将你的广告单元ID存储在strings.xml文件中。下面的ID仅用于测试,请确保在发布应用之前更改它。

<?xml version="1.0" encoding="utf-8"?>
<resources>    
    <string name="banner_ad_unit_id">ca-app-pub-3940256099942544/6300978111</string>
</resources>

检查所有这些,它应该工作。

mutmk8jj

mutmk8jj2#

mAdView.setAdListener(new AdListener() {
@Override
public void onAdLoaded() {
    // Code to be executed when an ad finishes loading.
}

@Override
public void onAdFailedToLoad(int errorCode) {
Log.d("errorcode",""+errorCode);
    // Code to be executed when an ad request fails.
}

@Override
public void onAdOpened() {
    // Code to be executed when an ad opens an overlay that
    // covers the screen.
}

@Override
public void onAdLeftApplication() {
    // Code to be executed when the user has left the app.
}

@Override
public void onAdClosed() {
    // Code to be executed when when the user is about to return
    // to the app after tapping on an ad.
}
});

把这个代码在onCreate(),广告侦听器和检查错误代码比说我的错误代码我给予你的解决方案.

s4n0splo

s4n0splo3#

您应该覆盖生命周期方法并在其中执行资源清理。

@Override
public void onPause() {
    if (mAdView != null) {
        mAdView.pause();
    }
    super.onPause();
}
@Override
public void onResume() {
    super.onResume();
    if (mAdView != null) {
        mAdView.resume();
    }
}
@Override
public void onDestroy() {
    if (mAdView != null) {
        mAdView.destroy();
    }
    super.onDestroy();

相关问题