简体   繁体   中英

Implementing admob for different activities

我总共有三个活动,我正在为每个活动实施 admob,每个活动都有自己的横幅,当活动发生变化时,另一个活动会因为后台的广告加载而挂起,有没有办法显示一个横幅在所有活动切换时避免延误。

you can do it just load ad in application class and use it in any activity.

you can download demo

as I do it,

App class

import android.app.Application;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;

public class App extends Application {

AdView adView;

@Override
public void onCreate() {
    // TODO Auto-generated method stub

    super.onCreate();

    adView = new AdView(this);
    adView.setAdSize(AdSize.SMART_BANNER);
    adView.setAdUnitId("ca-app-pub-1267746788642565/8418489933");
    // Request for Ads
    AdRequest adRequest = new AdRequest.Builder().build();

    // Load ads into Banner Ads
    adView.loadAd(adRequest);
}

public void loadAd(LinearLayout layAd) {

    // Locate the Banner Ad in activity xml
    if (adView.getParent() != null) {
        ViewGroup tempVg = (ViewGroup) adView.getParent();
        tempVg.removeView(adView);
    }

    layAd.addView(adView);

}
}

main Activity

public class MainActivity extends Activity {

App app;
LinearLayout layAd;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    layAd = (LinearLayout) findViewById(R.id.layad);

    app = (App) getApplication();
    app.loadAd(layAd);

    Button btnNext = (Button) findViewById(R.id.next);
    btnNext.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent iNext = new Intent(MainActivity.this,
                    SecondActivity.class);
            startActivity(iNext);
        }
    });
}

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    app.loadAd(layAd);
    super.onResume();
}
}

Second Activity

public class SecondActivity extends Activity {

App app;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_second);

    LinearLayout layAd = (LinearLayout) findViewById(R.id.layad);

    app = (App) getApplication();
    app.loadAd(layAd);
}
}

Manifest xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.admobdemo"
android:versionCode="1"
android:versionName="1.0" >

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

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="21" />

<application
    android:name="com.example.admobdemo.App"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.admobdemo.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name="com.example.admobdemo.SecondActivity"
        android:label="@string/app_name" >
    </activity>

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <activity
        android:name="com.google.android.gms.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" />
</application>
</manifest>

main activity layout xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >

<LinearLayout
    android:id="@+id/layad"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
</LinearLayout>

<Button
    android:id="@+id/next"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />
</LinearLayout>

and second activity layout xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="${relativePackage}.${activityClass}" >

<LinearLayout
    android:id="@+id/layad"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
</LinearLayout>
</LinearLayout>

The ideal way is to use fragments for each of your screens . This way, you'd use a single activity having a single adview.

If you want to use multiple activities instead, then the only workaround I know of is to use a static method to load the ads:

public class MyAdView {
    public static void SetAD(AdView adView){  
        AdRequest adRequest = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
            .build();
        adView.loadAd(adRequest);
    }

}

Usage:

public class SomeActivity extends Activity {
    private AdView adView;  

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.caller_main);
        MyAdView.SetAd((AdView)findViewById(R.id.adView));
    }   
}

I know this was answered a long time ago, but I think I have a better way for when you've already created your entire app with many activities. While RBK's solution is really good, it requires you to go through each activity's layout file and add the following LinearLayout:

<LinearLayout
    android:id="@+id/layad"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
</LinearLayout>

However, this can get really tedious if you have lots of different activities with lots of different layout files (especially if you're like me and forgot about admob integration until you finished the majority of the app). The simple improvement I found was creating a subclass of Activity or AppCompatActivity which handles placement and loading of the ads:

So similarly to RBK's solution, we create an Application class App . However, this will have a few small changes. Instead of placing our banner ad in a specific ViewGroup (like layad ) in our activites, we want it be automatically added to the bottom of an activity without us having to add anything to the layout file. We replace loadAd with a method that does this.

public class App extends Application {

    AdView adView;    

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub

        super.onCreate();

        adView = new AdView(this);
        adView.setAdSize(AdSize.SMART_BANNER);
        adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
        // Request for Ads
        AdRequest adRequest = new AdRequest.Builder().build();

        // Load ads into Banner Ads
        adView.loadAd(adRequest);
    }

    // run by each activity to show the banner ad on the bottom
    public void addBannerAdToActivity(AD_ACTIVITY context) {
        // get the root linear layout. We'll insert our banner ad at the end of it
        LinearLayout rootView = context.getRootLayout();

        // if the banner already has a parent, remove it...
        if (adView.getParent() != null) {
            ViewGroup par = (ViewGroup) adView.getParent();
            par.removeView(adView);
        }

        // set 'rootView' as the new parent of the banner:
        rootView.addView(adView);

        adView.setVisibility(View.VISIBLE); // just incase the banner isn't visible for some reason

        // Now the ad will be placed on the bottom of the activity requesting it
    }
}

Then we create an abstract class AD_ACTIVITY that extends AppCompatActivity :

public abstract class AD_ACTIVITY extends AppCompatActivity {
    
    private LinearLayout root;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // The content view of an AD_ACTIVITY is a linear layout with the first element being the main content and the second element being the banner ad:
        root = new LinearLayout(this); // create a new LinearLayout
        root.setOrientation(LinearLayout.VERTICAL);
   
        super.setContentView(root); // set that as the content view...
    }

    @Override
    public void setContentView(int layoutResID) {
        // Inflate the layout file and get a reference to it:
        ViewGroup inflatedView = (ViewGroup) ((LinearLayout) getLayoutInflater().inflate(layoutResID,root)).getChildAt(0);
        
        // we want the main content to take up the whole vertical screen with space at the bottom for the banner ad
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.weight = 1; // to do this, we set the weight of 'inflatedView' to 1
        inflatedView.setLayoutParams(params);

        // LOAD BANNER AD AND ADD IT TO 'root':
        ((App) getApplicationContext()).addBannerAdToActivity(this);
    }

    @Override
    protected void onResume() {
        super.onResume();

        // LOAD BANNER AD AND ADD IT TO 'root':
        ((App) getApplicationContext()).addBannerAdToActivity(this);
    }

    public LinearLayout getRootLayout() {
        return root;
    }
}

Now all we do is go through all activities and have it extend AD_ACTIVITY instead of AppCompatActivity . For example:

MainActivity.java :

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Gets changed to:

public class MainActivity extends AD_ACTIVITY {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

Changing the position of the banner, its behavior, and position is extremly easy to do since any changes done to AD_ACTIVITY will apply to all activities extending it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM