Sunday, 5 July 2020

Updated: Super fast way to implement latest Admob banner and Interstitial ads

I have something very cool for those who want to implement Admob ads in their Android apps.

This is just a five step process:
1) Add buildscript in build.gradle (project)
2) Add the dependency of Admob in build.gradle (module)
3) Initialize ads,
4) You only have to create an object of AdvertiseUtil.java class which has everything set,
5) Paste the banner ad's small code in your layout,
6) Just call the banner or interstitial ad whichever you want.
You are done!


------------------------------------------ build.gradle (project) ----------------------------------
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
}
}

plugins {
alias(libs.plugins.androidApplication) apply false
}
------------------------------------------------------------------------

------------------------------------------ build.gradle (module) ----------------------------------
apply plugin: 'com.android.application'

android {
compileSdkVersion 28
defaultConfig {
applicationId "com.app.yourappname"
minSdkVersion 16
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
implementation 'com.google.android.gms:play-services-ads:23.1.0'
}
------------------------------------------------------------------------


-------------------------------- string.xml ---------------------------
<resources>
<string name="app_name">WhatAnAndroid</string>

<!-- Admob Test Ads-->
<string name="ad_app_id">ca-app-pub-3940256099942544~3347511713</string>
<string name="ad_native">ca-app-pub-3940256099942544/2247696110</string>
<string name="ad_interstitial">ca-app-pub-3940256099942544/1033173712</string>
<string name="ad_banner">ca-app-pub-3940256099942544/6300978111</string>
<string name="ad_rewarded">ca-app-pub-3940256099942544/5224354917</string>
<!-- Admob Test Ads-->

</resources>
-------------------------------------------------

------------------------------ admob_ads_activity.xml -----------------------------------------------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_rll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/colorPrimary">

<RelativeLayout
android:gravity="center"
android:id="@+id/aaa_topBannerAdViewRL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"/>

<RelativeLayout
android:id="@+id/aaa_bottomBannerAdViewRL"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
</RelativeLayout>
</RelativeLayout>
-------------------------------------------------

------------------------------------- AdvertiseUtil.java ---------------------------------

import android.app.Activity;
import android.content.Context;

import androidx.annotation.NonNull;
import androidx.annotation.OptIn;
import androidx.media3.common.util.Log;
import androidx.media3.common.util.UnstableApi;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;
import com.prashantsj.apps.AdmobAdsActivity.R;

public class AdvertiseUtil {

private Context context;
private InterstitialAd mInterstitialAd;
public AdvertiseUtil(Context context) {
this.context = context;
}

/********************BANNER***********************/

private AdView adView;

public AdView loadBannerAd() {
adView = new AdView(context);
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId(context.getString(R.string.ad_bannerad));
showBanner();
return adView;
}

public void showBanner() {
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}

public void onResumeBanner(){
if(adView!=null)
adView.resume();
}

public void onPauseBanner(){
if(adView!=null)
adView.pause();
}

public void onDestroyBanner(){
if(adView!=null)
adView.destroy();
}

/*********************************************/

/*********************INTERSTITIAL*************************/

public void loadInterstitialAd() {
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(this.context, context.getString(R.string.ad_interstitial), adRequest,
             new InterstitialAdLoadCallback() {
@OptIn(markerClass = UnstableApi.class) @Override
public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i("Interstitial Ad Loaded", "onAdLoaded");
}

@Override
public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
// Handle the error
// Log.i("", loadAdError.toString());
mInterstitialAd = null;
}
});
}

public void showInterstitialAd() {
if (mInterstitialAd != null) {
mInterstitialAd.show((Activity) context);
loadInterstitialAd();
}
}

/*******************************************************/
}
-------------------------------------------------

------------------------------------- AdmobAdsActivity.java --------------------------
package com.app.yourappname;

import android.os.Bundle;
import android.widget.RelativeLayout;

import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.initialization.InitializationStatus;
import com.google.android.gms.ads.initialization.OnInitializationCompleteListener;
import com.app.yourappname.AdvertiseUtil;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class AdmobAdsActivity extends AppCompatActivity {

private AdvertiseUtil au;

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

setContentView(R.layout.admob_ads_activity);
MobileAds.initialize(this, initializationStatus -> {
        });

au = new AdvertiseUtil(this);

RelativeLayout topBanner = findViewById(R.id.aaa_topBannerAdViewRL);
RelativeLayout bottomBanner = findViewById(R.id.aaa_bottomBannerAdViewRL);

topBanner.addView(au.loadBannerAd());
bottomBanner.addView(au.loadBannerAd());

au.loadInterstitialAd();
}

@Override
public void onUserInteraction() {
super.onUserInteraction();

if(au!=null) au.showInterstitialAd();
}

@Override
protected void onPause() {
super.onPause();
if(au!=null) au.onPauseBanner();
}

@Override
protected void onResume() {
super.onResume();
if(au!=null) au.onResumeBanner();
}

@Override
protected void onDestroy() {
super.onDestroy();
if(au!=null) au.onDestroyBanner();
}
}
-------------------------------------------------

According to the new admob implementation rules, you need to add the app id in manifes
-------------------------- Declare the Activity name and internet permissions in manifest file-----------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.yourappname">

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

<application
    android:hardwareAccelerated="true"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:targetApi="31">
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="@string/ad_app_id"/>
<activity android:name=".AdmobAdsActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>



Wednesday, 1 July 2020

How to download, install and run Android Studio project on device?

Installing Android Studio is an easy process but sometimes if the correct procedure is not followed, things do not go right. So here is the complete step by step process to download, install and run your first app on device for Windows.


Step 1: Download the Android Studio IDE from https://developer.android.com/studio


Step 2: After opening the .exe or the setup file, you will see this window. I already have installed Android Studio so it is asking to Uninstall the old version. If you are installing fresh, no need to worry, just hit 'Next>' and go ahead by choosing a path where you would like it to be stored.


Step 3: After installing it successfully, a window will be opened (if you have selected start Android Studio after install finished). If not opened, then go to C:\Program Files\Android\Android Studio\bin\ and double click studio64.exe
For quick access create a desktop shortcut.

In this window, to create a new project, click on the first option: '+ Start a new Android Studio project'


Step 4: As the first project and program has to be simple, we will be creating an Empty Activity. Click on the 'Next' option.


Step 5: This window has multiple options to select from:
Name: You can set a name to your project under this field. 
Package name: This is a very important part of your app. A package differentiates your app from all other apps.
Save location: You can change the default project location by setting it here.
Language: Now there are two languages that support Android programming. Java and Kotlin. Though Kotlin is the official programming language of Android, I like Java. Again its your wish.
Minimum SDK: This option helps you to support you app for devices with old APIs. Setting it to API 16 shows support for 99.8% devices, so no need to change it.
Use Legacy android.support.libraries: This option is to be ticked when we want to include other libraries in our app. For now to make a hello world app, leave it unticked.

Please Note: Keep your internet connection ON before clicking finish.


Step 6: When the first project is created it will start downloading the necessary stuff. Let it finish downloading.


Step 7: After the downloading gets over, it may show error. If not then skip the steps.
For me, it was with error: Module 'app': platform 'android-29' not found.


Step 8: So lets see what is wrong. The android-29 is an api level for Android version 10.0 or Q. That means we have not installed android-29. In order to install it, click on the sdk manager shown with a red arrow.


  Step 9: After clicking on SDK manager, a window with all the apis will be displayed. Click the Show package details at the very right bottom corner so that you will be able to select necessary stuff individually.
Once you are able to see the selected Android SDK Platform 29, click Ok to continue installation.


Step 10: Read the 'Terms & Conditions' and select the 'Accept' radio button. Hit 'Next' to continue.


Step 11: Here you can understand why we did not download everything from Android 10.0 (Q) and rather selected just one from Show package details.
Click 'Ok'.

After successfully downloading it you will see no errors. But in order to run the app either you will need an Android device or an emulator.



Step 12: In your android device, go to Settings -> About Phone -> Build Number (See at the bottom). Tap 7 times on it to open the Developer option.



Step 13: The developer option will be enabled and can be found under Settings. Tap on it to open a new panel.


Step 14: In this step, connect your device to PC and keep the Android Studio IDE open. In device, keep two options ON in developer option. The first one is the main (at the top) and the another is USB debugging.



Step 15: Once all this done, you will see a window asking debugging permission (in your device) while showing your computer's RSA key. Allow it by pressing 'Ok' and finally in the Android Studio, you will see your device's name at the place where the red arrow is pointing. If your emulator is already opened, click the drop down option.


 
Congratulations! you are able to show the output on your phone through USB debugging.

To avoid attaching USB connection and to enjoy wireless WIFI debugging please follow the link:
http://whatanandroid.blogspot.com/2020/07/how-to-do-wireless-debugging-in-android.html

How to do Wireless debugging in Android?

In this tutorial we will be learning a new way of debugging which reduces the headache of USB cable connection.

For this, we have two options: either we can follow the Google's documentation or attach a plugin. This blog is about attaching a third party plugin into your project.

You will have to keep the debugging ON in your device.
If you are not sure how to do that, please refer to this link:
http://whatanandroid.blogspot.com/2020/07/how-to-download-install-and-run-android.html

What is mandatory?
Your device (Phone, Tablet, etc) and the laptop/PC must be connected to a common WIFI.

Just follow these steps and all will be set:



Step 1: For the first time attach the device with USB cable by setting the developer's option ON 


Step 2: Keep the internet connection ON and Go to File->Settings


Step 3: There are many plugins available on the net. I had tried the Android WifiADB plugin and it worked. So select this plugin and click on install. After that a pop up will appear to ask restarting the IDE'. Click on Restart option.

Please note: 
Check if your ADB path is set by typing 'adb' in the command prompt.
If you have already set the ADB path, SKIP the Steps 4, 5, 6 & 7.


Step 4: Right click 'This PC' and go to 'Properties' option.


Step 5: Click on 'Advanced system settings'


Step 6: Click on Environment Variables


Step 7: In the path of User variables and System variables paste the path of your adb.exe file which is (in windows) by default located at 'C:\Users\[user]\AppData\Local\Android\sdk\platform-tools'. So in this case you should paste this in your both paths mentioned above (Do not forget to add a ; at end)  C:\Users\[user]\AppData\Local\Android\sdk\platform-tools;


Step 8: Keep your device connected and go to Tools -> WifiADB



Step 9: The final step is to connect your device by clicking on the 'connect' option.
The device name will be shown under 'name' section.


You can disconnect the connection by clicking on the red colored option 'disconnect'.


Here is the final output.