I want to add advertising in android application - android

I want to add "ads" in my project. I have created an ad using the website admob.com I just need to know how can i add it to my project. I searched on google but I am not getting the correct answers. Please Help. Thanks in advance.

Here are simple steps to add an ad banner in your android app.
Firstly add this method in your Main activity
private void displayAd()
{
try
{
AdView adView = new AdView(LettersType.this, AdSize.BANNER, HERE-YOUR-ADMOB-ID);
// Lookup your LinearLayout assuming it’s been given
// the attribute android:id="#+id/mainLayout"
FrameLayout adMobLayout = (FrameLayout)findViewById(R.id.banner);
// Add the adView to it
adMobLayout.addView(adView);
// AdRequest adRequest = new AdRequest();
// adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
// Initiate a generic request to load it with an ad
adView.loadAd(new AdRequest());
adView.setAdListener(new AdListener() {
public void onDismissScreen(Ad arg0) {
}
public void onLeaveApplication(Ad arg0) {
}
public void onPresentScreen(Ad arg0) {
}
public void onReceiveAd(Ad arg0) {
}
public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
}
});
}catch(Exception e)
{
}
}
Add this permissions in android manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<activity android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
And finally add this in your mainactivity layout XML file
<FrameLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/banner"
android:layout_centerHorizontal="true"
/>
This framelayout is the adbanner .

Related

Android GeoLocation doesn't work on device

I'm writing a basic mobile wrapper that connects to a site mainly using Javascript. This site has a login form that tries to access the geolocation of the device in question. When run on an emulator, there is no prompt to allow location (which makes sense in my mind since the PC has a physical location and an external IP address etc) and the GeoLocation just goes through no problem, which to me suggests that the code is at least functional as far as permissions and webView settings go. When run on a device which has location services enabled, even if I'm prompted and allow location the site cannot resolve my location.
The webView and settings are shown below, and the Android Manifest below that.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wView = (WebView) findViewById(R.id.activity_main_webview);
WebView.setWebContentsDebuggingEnabled(true);
wView.setWebChromeClient(new WebChromeClient(){
#Override
public void onGeolocationPermissionsShowPrompt(final String origin,
final GeolocationPermissions.Callback callback) {
AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
builder.setMessage( origin + " would like to use your current location" );
builder.setNegativeButton( "Don't Allow", new DialogInterface.OnClickListener() {
#Override
public void onClick( DialogInterface dialog, int which ) {
callback.invoke( origin, false, false );
dialog.dismiss();
}
} );
builder.setPositiveButton( "Okay", new DialogInterface.OnClickListener() {
#Override
public void onClick( DialogInterface dialog, int which ) {
callback.invoke( origin, true, false );
dialog.dismiss();
}
});
}
});
wView.getSettings().setJavaScriptEnabled(true);
wView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
wView.getSettings().setGeolocationEnabled(true);
String url = BuildConfig.HOST_URL;
//String postData = "username="+ URLEncoder.encode(user,"UTF-8")+"&password="+URLEncoder.encode(password,"UTF-8");
//Log.e("TEST","postData " + postData);
wView.loadUrl(url);
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.toteireland.app" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="Tote Ireland"
android:theme="#style/AppTheme"
>
<activity
android:name="com.toteireland.app.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>
</application>
Is that the right place for the permissions?

AdMob interstitial ad not loading

The interstitial ad won't show in my application, I don't know what to do anymore.
Note:
My app isn't listed in Google's Play store yet. I hope this isn't causing the fault.
What have I done:
I have created a new interstitial ad on the admob's site.
I have added Google Play to my project:
-
<activity
android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:theme="#style/AppTheme.NoActionBar" />
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
The Google Play service version is:
<integer name="google_play_services_version">6171000</integer>
I have added the InterstitialAd object
-
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
private InterstitialAd mInterstitialAd;
#Override
protected void onCreate(Bundle savedInstance) {
//
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId(AD_UNIT_ID);
mInterstitialAd.setAdListener(mAdListener);
AdRequest.Builder builder = new AdRequest.Builder();
mInterstitialAd.loadAd(builder.build());
}
And the ad listener:
-
private AdListener mAdListener = new AdListener() {
#Override
public void onAdLoaded() {
super.onAdLoaded();
Functions.log("Ad loaded !");
}
}
The method: onAdLoaded() isn't called. I left the application for 5 minutes but I got no response.
I have even tried to force show()
findViewById(R.id.btn_testAd).setOnClickListener(new View.OnCliclIstener() {
#Override
public void onClick(View v) {
mInterstitialAd.show();
}
});
What have I got in the logcat:
The interstitial has not loaded.
Sometimes programming is a pain.
I forgot to declare the permissions in the manifest file.
<!-- Used to request banner and interstitial ads. -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Used to avoid sending an ad request if there is no connectivity. -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- Required permissions for video ads. -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

AdMob: "activity has leaked ServiceConnection" and "AdvertisingIdClient unbindService failed."

I'm using AdMob in my app. I followed implementation guidelines, and the banner is correctly showing and loading the ads. My MainActivity is responsible of creating references, building the AdRequest and showing the banner, as well as pausing, resuming, and destroying the AdView. Everytime the AdRequest has been loaded, when the Activity's onStop() is called, the following Exception is created:
6706-6706/com.rocca.controlloSpese E/ActivityThread﹕ Activity com.rocca.controlloSpese.MainActivity has leaked ServiceConnection com.google.android.gms.common.b#52b1cc3c that was originally bound here
android.app.ServiceConnectionLeaked: Activity com.rocca.controlloSpese.MainActivity has leaked ServiceConnection com.google.android.gms.common.b#52b1cc3c that was originally bound here
at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:970)
at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:864)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1577)
at android.app.ContextImpl.bindService(ContextImpl.java:1560)
at android.content.ContextWrapper.bindService(ContextWrapper.java:517)
at com.google.android.gms.ads.identifier.a.b(SourceFile:330)
at com.google.android.gms.ads.identifier.a.a(SourceFile:187)
at com.google.android.gms.ads.identifier.a.b(SourceFile:239)
at com.google.android.a.t.f(SourceFile:132)
at com.google.android.a.t.b(SourceFile:182)
at com.google.android.a.q.a(SourceFile:258)
at com.google.android.a.q.a(SourceFile:195)
at com.google.android.gms.ads.internal.m.a(SourceFile:107)
at com.google.android.gms.ads.internal.request.c.a(SourceFile:99)
at com.google.android.gms.ads.internal.util.b.run(SourceFile:17)
at com.google.android.gms.ads.internal.util.d.call(SourceFile:29)
at com.google.android.gms.ads.internal.util.e.call(SourceFile:49)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
followed by this info:
6706-6781/com.rocca.controlloSpese I/AdvertisingIdClient﹕ AdvertisingIdClient unbindService failed.
java.lang.IllegalArgumentException: Service not registered: com.google.android.gms.common.b#52b1cc3c
at android.app.LoadedApk.forgetServiceDispatcher(LoadedApk.java:922)
at android.app.ContextImpl.unbindService(ContextImpl.java:1611)
at android.content.ContextWrapper.unbindService(ContextWrapper.java:529)
at com.google.android.gms.ads.identifier.a.c(SourceFile:275)
at com.google.android.gms.ads.identifier.b.c(SourceFile:100)
at com.google.android.gms.ads.identifier.b.run(SourceFile:110)
This doesn't happen if the AdRequest is not built and loaded. I set up my IABHelper in onCreate(), and if the user didn't buy my "remove-ads" sku, ads are shown. This is the code I use to load the ads:
private void showAds() {
int adresult = GooglePlayServicesUtil.isGooglePlayServicesAvailable(MainActivity.this);
if (adresult == ConnectionResult.SUCCESS) {
//if possible, show ads
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
.addTestDevice("C144E9DA02EA7B26F74ED2C231F31D38")
.addTestDevice("93BABD84466B8C1EF529D2FB39D1ACE8")
.addTestDevice("BEAA738068664AE9BBF673E37A782E03")
.addTestDevice("E51508081F77DF84C129EE471DE67141")
.build();
adView.setVisibility(View.VISIBLE);
adView.loadAd(adRequest);
} else {
//if there's a problem, show error and close app
GooglePlayServicesUtil.getErrorDialog(adresult, MainActivity.this, 0, new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialogInterface) {
finish();
}
}).show();
}
}
adView's pause(), resume() and destroy() are called in the respective activity's methods. Practically, the app's performance isn't affected, but I'd rather avoid memory leaks. How do I avoid that exception?
EDIT: the Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.rocca.controlloSpese" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.android.vending.BILLING" />
<uses-permission android:name="com.rocca.controlloSpese.BROADCAST_PERMISSION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:finishOnCloseSystemDialogs="true"
android:label="#string/app_name"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</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>
I'm seeing exactly the same behaviour just using the example quick start project from the AdMob website here. I'm seeing this running Lollipop on a Nexus 5.
Therefore this looks like an AdMob bug to me.
Is there anyway to get a reference to the AdMob service and unbind the service manually to see if that stops the error?
Below code solve my problem;
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
mAdView.destroy();
super.onDestroy();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mAdView.resume();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mAdView.pause();
}

ADMOB - The following classes could not be instantiated: - com.google.android.gms.ads.AdView

I updated my old admob to the new admob. I downloaded SDK, imported google play service library and done everything in google documantation. But when I add the xml code:
<com.google.android.gms.ads.AdView android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adUnitId="ca-app-pub-XXXXXXXXXXXXXXX/YYYYYYYY"
ads:adSize="BANNER"/>
I get the following message in error log:
The following classes could not be instantiated: - com.google.android.gms.ads.AdView
There is Manifest XML code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<activity
android:name=".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.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Coul you help me please?
You can create AdView in java code, but not in xml.
it works for me:
private AdView adView;
private static final String AD_UNIT_ID = "XXXXXXX";
#Override
public void onCreate(){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create an ad.
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(AD_UNIT_ID);
// Add the AdView to the view hierarchy. The view will have no size
// until the ad is loaded.
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
layout.addView(adView);
// Create an ad request. Check logcat output for the 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();
// Start loading the ad in the background.
adView.loadAd(adRequest);
}
#Override
public void onResume() {
super.onResume();
if (adView != null) {
adView.resume();
}
}
#Override
public void onPause() {
if (adView != null) {
adView.pause();
}
super.onPause();
}
/** Called before the activity is destroyed. */
#Override
public void onDestroy() {
// Destroy the AdView.
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
Have you edited the proguard-project.txt? If not then open the proguard-project.txt file and put these lines there...
-keep public class com.google.android.gms.ads.** {
public *;
}
-keep public class com.google.ads.** {
public *;
}
Set target=android-13 or higher in your project.properties.

Admob Banner Ad not displaying in Android

Hi I have a Android game app developed using android cocos2d i need to integrate admob i have included the following code but banner ad is not displaying please help regarding this your answers will be appreciated and it would be a great help. thank you.
public class MainActivity extends Activity {
private CCGLSurfaceView mGLSurfaceView;
private boolean isCreated = false;
public static FrameLayout m_rootLayout;
AdView adView;
// This is used to display Toast messages and is not necessary for your app
#Override
protected void onCreate(Bundle savedInstanceState) {
if (!isCreated) {
isCreated = true;
} else {
return;
}
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
try{
LinearLayout.LayoutParams adParams = new LinearLayout.LayoutParams(
getWindowManager().getDefaultDisplay().getWidth(),
getWindowManager().getDefaultDisplay().getHeight()+getWindowManager().getDefaultDisplay().getHeight()-50);
adView = new AdView(this, AdSize.BANNER, "admob id");
AdRequest request = new AdRequest();
adView.loadAd(request);
// Adding full screen container
addContentView(adView, adParams);
}catch (Exception e) {
FlurryAgent.logEvent("ADMOB ERROR: "+e);
}
mGLSurfaceView = new CCGLSurfaceView(this);
setContentView(mGLSurfaceView);
CCDirector.sharedDirector().attachInView(mGLSurfaceView);
getScaledCoordinate();
Global.assetManager = getAssets();
Global.context = this;
Global.loadUserInfo();
CCScene scene = CCScene.node();
scene.addChild(new SplashScene(), -1);
CCDirector.sharedDirector().runWithScene(scene);
//-------------IAP-----------------------
Log.d(TAG1, "Creating IAB helper.");
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.enableDebugLogging(true);
Log.d(TAG1, "Starting setup.");
mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
Log.d(TAG, "Setup finished.");
if (!result.isSuccess()) {
// Oh noes, there was a problem.
complain("Problem setting up in-app billing: " + result);
return;
}
// Hooray, IAB is fully set up. Now, let's get an inventory of stuff we own.
Log.d(TAG, "Setup successful. Querying inventory.");
mHelper.queryInventoryAsync(mGotInventoryListener);
}
});
Global.myActivity=this;
}
manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.game.puzzlegame"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.android.vending.BILLING" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.game.puzzlegame.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.revmob.ads.fullscreen.FullscreenActivity"
android:configChanges="keyboardHidden|orientation" >
</activity>
<activity android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"></activity>
</application>
Please review all these additions in your project.
In Java class:
AdView layout = (AdView)this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest();
//adRequest.setTesting(true);
layout.loadAd(adRequest);
In Layout:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads">
<com.google.ads.AdView
android:id="#+id/adView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="your key" />
</LinearLayout>
In Manifest:
<activity android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation" />
I have worked with AdMob Lib. Ver. 4.0.4 which worked fine in my case.
Try this code
LinearLayout.LayoutParams adParams = new LinearLayout.LayoutParams(
getWindowManager().getDefaultDisplay().getWidth(),
getWindowManager().getDefaultDisplay().getHeight()+getWindowManager().getDefaultDisplay().getHeight()-50);
AdView ad = new AdView(this, AdSize.BANNER, "admob_id");
adParams.addView(ad);
AdRequest r = new AdRequest();
//r.setTesting(true);
ad.loadAd(r);
Make sure that you included correct ID and have correspond permissions for your app.
In addition it would be good to implement ADListener that really displays what how its going with ads rendering.
Also don't forget to set test mode to query ads, AdMob guys can just ban you for irresponsible clicks.
for latest Ads in Android
use below code
AdView layout = (AdView) this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.build();
//adRequest.setTesting(true);
layout.loadAd(adRequest);
beacuse AdRequest class final class so we can not create object.

Categories

Resources