Google Admob implementation : Interstitial

Before Follow this tutorial please first complete the project configuration about how to integrate admob in android . 

 

Step 1 :Create an interstitial ad object

Interstitial ads are requested and shown by InterstitialAd objects. The first step is instantiating InterstitialAd and setting its ad unit ID. This is done in the onCreate() method of an Activity:

[java]
import com.google.android.gms.ads.InterstitialAd;

public class MainActivity extends Activity {

private InterstitialAd mInterstitialAd;

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

MobileAds.initialize(this,
"ca-app-pub-3940256099942544~3347511713");

mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
}
}
[/java]

Step 2 : Always test with test ads

When building and testing your apps, make sure you use test ads rather than live, production ads. Failure to do so can lead to suspension of your account.

The easiest way to load test ads is to use our dedicated test ad unit ID for Android interstitials:

ca-app-pub-3940256099942544/1033173712

Step 3 : Load an ad

Note: Make all calls to the Mobile Ads SDK on the main thread.
To load an interstitial ad, call the InterstitialAd object’s loadAd() method. This method accepts an AdRequest object as its single parameter:

[java]

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;

public class MainActivity extends Activity {

private InterstitialAd mInterstitialAd;

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

MobileAds.initialize(this,
"ca-app-pub-3940256099942544~3347511713");

mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
}
[/java]

Step 4 : Show the ad

Interstitial ads should be displayed during natural pauses in the flow of an app. Between levels of a game is a good example, or after the user completes a task. To show an interstitial, use the isLoaded() method to verify that it’s done loading, then call show(). The interstitial ad from the previous code example could be shown in a button’s OnClickListener like this:

[java]
mMyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn’t loaded yet.");
}
}
});
[/java]

Step 5: Ad events

To further customize the behavior of your ad, you can hook onto a number of events in the ad’s lifecycle: loading, opening, closing, and so on. You can listen for these events through the AdListener class.

To use an AdListener with an InterstitialAd object, simply call the setAdListener() method:

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

@Override
public void onAdFailedToLoad(int errorCode) {
// Code to be executed when an ad request fails.
}

@Override
public void onAdOpened() {
// Code to be executed when the ad is displayed.
}

@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 interstitial ad is closed.
}
});
[/java]

Step 6 : Using an AdListener to reload

The AdListener class’s onAdClosed() method is a handy place to load a new interstitial after displaying the previous one:

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

MobileAds.initialize(this,
"ca-app-pub-3940256099942544~3347511713");

mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());

mInterstitialAd.setAdListener(new AdListener() {
@Override
public void onAdClosed() {
// Load the next interstitial.
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}

});
}
[/java]

Unity touch to swipe left right forward and back(down) : mobile input for android and IOS – Complete Script

[java]

using UnityEngine;

public class Swipe : MonoBehaviour
{
private Vector2 fingerDown;
private Vector2 fingerUp;
public bool detectSwipeOnlyAfterRelease = false;

public float SWIPE_THRESHOLD = 20f;
public GameObject gameObeject;
public float moveSpeed = 200f;

void Start(){

//Rigidbody rb = GetComponent<Rigidbody>();
}

// Update is called once per frame
void Update()
{

foreach (Touch touch in Input.touches)
{
if (touch.phase == TouchPhase.Began)
{
fingerUp = touch.position;
fingerDown = touch.position;
}

//Detects Swipe while finger is still moving
if (touch.phase == TouchPhase.Moved)
{
if (!detectSwipeOnlyAfterRelease)
{
fingerDown = touch.position;
checkSwipe();
}
}

//Detects swipe after finger is released
if (touch.phase == TouchPhase.Ended)
{
fingerDown = touch.position;
checkSwipe();
}
}
}

void checkSwipe()
{
//Check if Vertical swipe
if (verticalMove() > SWIPE_THRESHOLD && verticalMove() > horizontalValMove())
{
//Debug.Log("Vertical");
if (fingerDown.y – fingerUp.y > 0)//up swipe
{
OnSwipeUp();
}
else if (fingerDown.y – fingerUp.y < 0)//Down swipe { OnSwipeDown(); } fingerUp = fingerDown; } //Check if Horizontal swipe else if (horizontalValMove() > SWIPE_THRESHOLD && horizontalValMove() > verticalMove())
{
//Debug.Log("Horizontal");
if (fingerDown.x – fingerUp.x > 0)//Right swipe
{
OnSwipeRight();
}
else if (fingerDown.x – fingerUp.x < 0)//Left swipe
{
OnSwipeLeft();
}
fingerUp = fingerDown;
}

//No Movement at-all
else
{
//Debug.Log("No Swipe!");
}
}

float verticalMove()
{
return Mathf.Abs(fingerDown.y – fingerUp.y);
}

float horizontalValMove()
{
return Mathf.Abs(fingerDown.x – fingerUp.x);
}

//////////////////////////////////CALLBACK FUNCTIONS/////////////////////////////
void OnSwipeUp()
{
Debug.Log("Swipe UP");
transform.Translate(Vector3.forward * moveSpeed * Time.deltaTime);
}

void OnSwipeDown()
{
Debug.Log("Swipe Down");
transform.Translate(Vector3.back * moveSpeed * Time.deltaTime);
}

void OnSwipeLeft()
{
Debug.Log("Swipe Left");
transform.Translate(Vector3.left * moveSpeed * Time.deltaTime);
}

void OnSwipeRight()
{
Debug.Log("Swipe Right");
transform.Translate(Vector3.right * moveSpeed * Time.deltaTime);
}
}
[/java]

Download Project

Error:Execution failed for task

Error:Execution failed for task ‘:app:transformDexArchiveWithDexMergerForDebug’. > com.android.build.api.transform.TransformException: com.android.dex.DexException: Multiple dex files define Lcom/google/android/gms/internal/measurement/zzws;

 

update the google-service plugin to:

classpath ‘com.google.gms:google-services:3.3.0’

Error:Execution failed for task ‘:app:processDebugGoogleServices’. > Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 11.4.2.

Solution : Check all google version is same. If google play service is different then others then there may create conflict. Firebase and others google services should be in same version.

Example :

[java]
dependencies {
implementation fileTree(dir: ‘libs’, include: [‘*.jar’])
implementation ‘com.android.support:appcompat-v7:26.1.0’
implementation ‘com.android.support.constraint:constraint-layout:1.0.2’
implementation ‘com.android.support:design:26.1.0’
testImplementation ‘junit:junit:4.12’
androidTestImplementation ‘com.android.support.test:runner:1.0.1’
androidTestImplementation ‘com.android.support.test.espresso:espresso-core:3.0.1’
//noinspection GradleCompatible
implementation ‘com.google.android.gms:play-services-ads:15.0.0’

compile ‘com.google.firebase:firebase-core:15.0.0’
compile ‘com.google.firebase:firebase-database:15.0.0’
compile ‘com.google.firebase:firebase-firestore:15.0.0’
compile ‘com.google.firebase:firebase-storage:15.0.0’
compile ‘com.google.firebase:firebase-crash:15.0.0’
compile ‘com.google.firebase:firebase-auth:15.0.0’
compile ‘com.google.firebase:firebase-messaging:15.0.0’
compile ‘com.google.firebase:firebase-ads:15.0.0’
compile ‘com.google.firebase:firebase-appindexing:15.0.0’
compile ‘com.google.firebase:firebase-config:15.0.0’
compile ‘com.google.firebase:firebase-invites:15.0.0’
compile ‘com.google.firebase:firebase-perf:15.0.0’
compile ‘com.android.support:cardview-v7:26.1.0’
compile ‘com.android.support:recyclerview-v7:26.1.0’
compile ‘com.android.support:multidex:+’
apply plugin: ‘com.google.gms.google-services’

}

[/java]

Google Admob implementation on android project

All are described here here https://developers.google.com/admob/android/quick-start.
I am only arrange step by step procedure-

Step 1 :
Example project-level build.gradle (excerpt)
add this on build.gradle(global) in repositories brackets

[java]
maven {
url "https://maven.google.com"
}
[/java]

as like –

[java]
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}

[/java]

Step 2 :

[java]
Example app-level build.gradle (excerpt)
dependencies {
implementation fileTree(dir: ‘libs’, include: [‘*.jar’])
implementation ‘com.android.support:appcompat-v7:26.1.0’
implementation ‘com.google.android.gms:play-services-ads:15.0.0’
}

[/java]

Step 3 :

Update your AndroidManifest.xml
Add your AdMob App ID to your app’s AndroidManifest.xml file by adding the tag shown below. You can find your App ID in the AdMob UI.

[java]
<manifest>
<application>
<!– Sample AdMob App ID: ca-app-pub-3940256099942544~3347511713 –>
<meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="REPLACE_WITH_YOUR_ADMOB_APP_ID"/>
</application>
</manifest>

[/java]

Step 4 :

Before loading ads, have your app initialize the Mobile Ads SDK by calling MobileAds.initialize() with your AdMob App ID. This needs to be done only once, ideally at app launch.

Here’s an example of how to call the initialize() method in an Activity:

Example MainActivity (excerpt)

[java]
import com.google.android.gms.ads.MobileAds;

public class MainActivity extends AppCompatActivity {

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

// Sample AdMob app ID: ca-app-pub-3940256099942544~3347511713
MobileAds.initialize(this, "YOUR_ADMOB_APP_ID");
}

}
[/java]

So basic works is done . Now our app is ready to implement Banner , Interstitial and Rewards Video ads.

1 : How to implement Banner Ads
2 : How to implement Interstitial Ads
3 : How to implement Rewards Video Ads

Android multiple runtime permission

Step -1 : Add the permissions on Menifest.

[java]
 &amp;amp;amp;amp;amp;amp;lt;uses-permission android:name="android.permission.RECORD_AUDIO" /&amp;amp;amp;amp;amp;amp;gt;
    &amp;amp;amp;amp;amp;amp;lt;uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /&amp;amp;amp;amp;amp;amp;gt;
    &amp;amp;amp;amp;amp;amp;lt;uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"&amp;amp;amp;amp;amp;amp;gt;&amp;amp;amp;amp;amp;amp;lt;/uses-permission&amp;amp;amp;amp;amp;amp;gt;

[/java]

Step 2 : Request for permissions

[java]
//Permission function starts from here
    private void RequestMultiplePermission() {

        // Creating String Array with Permissions.
        ActivityCompat.requestPermissions(MainActivity.this, new String[]
                {
                        READ_EXTERNAL_STORAGE,
                        RECORD_AUDIO,
                        WRITE_EXTERNAL_STORAGE,

                }, RequestPermissionCode);

    }

    // Calling override method.
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {

            case RequestPermissionCode:

                if (grantResults.length &amp;amp;amp;amp;amp;amp;gt; 0) {

                    boolean readExternalStorage = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                    boolean recordAudio = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                    boolean writeExternalStorage = grantResults[2] == PackageManager.PERMISSION_GRANTED;

                    if (readExternalStorage &amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp; recordAudio &amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp; writeExternalStorage ) {

                        Toast.makeText(MainActivity.this, "Permission Granted", Toast.LENGTH_LONG).show();
                    }
                    else {
                        Toast.makeText(MainActivity.this,"Permission Denied",Toast.LENGTH_LONG).show();

                    }
                }

                break;
        }
    }
[/java]

Step 3: Check permissions

[java]
  // Checking permission is enabled or not using function starts from here.
    public boolean CheckingPermissionIsEnabledOrNot() {

        int recordAudio = ContextCompat.checkSelfPermission(getApplicationContext(), RECORD_AUDIO);
        int readExternalStorage = ContextCompat.checkSelfPermission(getApplicationContext(), READ_EXTERNAL_STORAGE);
        int writeExternalStorage = ContextCompat.checkSelfPermission(getApplicationContext(), WRITE_EXTERNAL_STORAGE);

        return recordAudio == PackageManager.PERMISSION_GRANTED &amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;
                readExternalStorage == PackageManager.PERMISSION_GRANTED &amp;amp;amp;amp;amp;amp;amp;&amp;amp;amp;amp;amp;amp;amp;
                writeExternalStorage == PackageManager.PERMISSION_GRANTED;
    }
[/java]

Step 4 : Call it on OnCreate to check permissions are granted or not.

[java]
   if(CheckingPermissionIsEnabledOrNot())
        {
            Toast.makeText(MainActivity.this, "All Permissions Granted Successfully", Toast.LENGTH_LONG).show();
        }

        // If, If permission is not enabled then else condition will execute.
        else {

            //Calling method to enable permission.
            RequestMultiplePermission();

        }
[/java]

Full Code

 [java][/java]

import android.Manifest;

import android.app.Activity;

import android.content.Context;

import android.content.DialogInterface;

import android.content.pm.PackageManager;

import android.os.Build;

import android.os.Bundle;

import android.support.design.widget.FloatingActionButton;

import android.support.design.widget.Snackbar;

import android.support.v4.app.ActivityCompat;

import android.support.v4.content.ContextCompat;

import android.support.v7.app.AppCompatActivity;

import android.support.v7.widget.Toolbar;

import android.view.View;

import android.view.Menu;

import android.view.MenuItem;

import android.widget.Button;

import android.widget.Toast;



import android.app.AlertDialog;

public class MainActivity extends AppCompatActivity {

private static final int MY_PERMISSIONS_REQUEST_CODE = 123;



private Context mContext;

private Activity mActivity;

private Button permissionCheck;



@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

setSupportActionBar(toolbar);



// Get the application context

mContext = getApplicationContext();

mActivity = MainActivity.this;



permissionCheck = findViewById(R.id.permission_check);

permissionCheck.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){

checkPermission();

}

}

});
}

protected void checkPermission(){

if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.CAMERA)

+ ContextCompat.checkSelfPermission(

mActivity,Manifest.permission.READ_CONTACTS)

+ ContextCompat.checkSelfPermission(

mActivity,Manifest.permission.WRITE_EXTERNAL_STORAGE)

!= PackageManager.PERMISSION_GRANTED){



// Do something, when permissions not granted

if(ActivityCompat.shouldShowRequestPermissionRationale(

mActivity,Manifest.permission.CAMERA)

|| ActivityCompat.shouldShowRequestPermissionRationale(

mActivity,Manifest.permission.READ_CONTACTS)

|| ActivityCompat.shouldShowRequestPermissionRationale(

mActivity,Manifest.permission.WRITE_EXTERNAL_STORAGE)){

// If we should give explanation of requested permissions



// Show an alert dialog here with request explanation

AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);

builder.setMessage("Camera, Read Contacts and Write External" +

" Storage permissions are required to do the task.");

builder.setTitle("Please grant those permissions");

builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialogInterface, int i) {

ActivityCompat.requestPermissions(

mActivity,

new String[]{

Manifest.permission.CAMERA,

Manifest.permission.READ_CONTACTS,

Manifest.permission.WRITE_EXTERNAL_STORAGE

},

MY_PERMISSIONS_REQUEST_CODE

);

}

});

builder.setNeutralButton("Cancel",null);

AlertDialog dialog = builder.create();

dialog.show();

}else{

// Directly request for required permissions, without explanation

ActivityCompat.requestPermissions(

mActivity,

new String[]{

Manifest.permission.CAMERA,

Manifest.permission.READ_CONTACTS,

Manifest.permission.WRITE_EXTERNAL_STORAGE

},

MY_PERMISSIONS_REQUEST_CODE

);

}

}else {

// Do something, when permissions are already granted

Toast.makeText(mContext,"Permissions already granted",Toast.LENGTH_SHORT).show();

}

}



@Override

public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){

switch (requestCode){

case MY_PERMISSIONS_REQUEST_CODE:{

// When request is cancelled, the results array are empty

if(

(grantResults.length >0) &&

(grantResults[0]

+ grantResults[1]

+ grantResults[2]

== PackageManager.PERMISSION_GRANTED

)

){

// Permissions are granted

Toast.makeText(mContext,"Permissions granted.",Toast.LENGTH_SHORT).show();

}else {

// Permissions are denied

Toast.makeText(mContext,"Permissions denied.",Toast.LENGTH_SHORT).show();

}

return;

}

}

}

}

Download From Github

https://github.com/arifhasnatnstucsteonGit/Android_Multiple_Runtime_Permission

Unity google admob implementation

Part 1 : Go to the git repository and download/clone it https://github.com/googleads/googleads-mobile-unity
Part 2:  Download unity google admob latest plugin https://github.com/googleads/googleads-mobile-unity/releases
Part 3 Create a Unity Project and import the plugin
Part 4: Go to following directory of the repository you download of step 1 : google admob plugins\googleads-mobile-unity-master\googleads-mobile-unity-master\samples\HelloWorld\Assets\Scripts
Part 5 : Copy the script to the assset folder
Part 6 : Attach the script to MainCamera.
Part 7: It should show default ads when you will build it for android or iOS .

You can now customize it for different uses like game over case and etc.

 

Download Project 

Unity play background music without restart the music when scene reloaded

Step 1:  
Create an empty game object named like BackgroundMusic. and add a tag name like “BackgroudMusic”.
Step 2:
Add a AudioSource and attach a music on that.
Step 3: 

Create C# script named Background music or anything else . Attach the code to the gameObject

[java]
using UnityEngine;
using System.Collections;

public class BackgroundMusic : MonoBehaviour {

private GameObject[] music;

void Start(){
music = GameObject.FindGameObjectsWithTag ("BackgroundMusic");
if(music.Length > 0) {
Destroy (music[1]);
}

}

// Update is called once per frame
void Awake () {
DontDestroyOnLoad (transform.gameObject);
}
}

[/java]