Monday, August 31, 2015

how to backup contacts or sms to SD card as .xml file or .csv file and restore it later

Step 1 To Take Backup

 public ArrayList<String> smsBuffer = new ArrayList<String>();
    String smsFile = "SMS"+".csv";
       private void  backupSMS(){
    smsBuffer.clear();
    Uri mSmsinboxQueryUri = Uri.parse("content://sms");
    Cursor cursor1 = getContentResolver().query(
            mSmsinboxQueryUri,
            new String[] { "_id", "thread_id", "address", "person", "date",
                    "body", "type" }, null, null, null);
    //startManagingCursor(cursor1);
    String[] columns = new String[] { "_id", "thread_id", "address", "person", "date", "body",
            "type" };
    if (cursor1.getCount() > 0) {
        String count = Integer.toString(cursor1.getCount());
        Log.d("Count",count);
        while (cursor1.moveToNext()) {

             String messageId = cursor1.getString(cursor1
                    .getColumnIndex(columns[0]));

             String threadId = cursor1.getString(cursor1
                    .getColumnIndex(columns[1]));

            String address = cursor1.getString(cursor1
                    .getColumnIndex(columns[2]));
            String name = cursor1.getString(cursor1
                    .getColumnIndex(columns[3]));
            String date = cursor1.getString(cursor1
                    .getColumnIndex(columns[4]));
            String msg = cursor1.getString(cursor1
                    .getColumnIndex(columns[5]));
            String type = cursor1.getString(cursor1
                    .getColumnIndex(columns[6]));

            smsBuffer.add(messageId + ","+ threadId+ ","+ address + "," + name + "," + date + " ," + msg + " ,"
                    + type);
        }           
        generateCSVFileForSMS(smsBuffer);
    }               
}

 private void generateCSVFileForSMS(ArrayList<String> list)
{

    try 
    {
        String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + smsFile;
        FileWriter write = new FileWriter(storage_path);

        write.append("messageId, threadId, Address, Name, Date, msg, type");
        write.append('\n');

        for (String s : list)
        {
            write.append(s);
            write.append('\n');
        }
        write.flush();
        write.close();
    }

    catch (NullPointerException e) 
    {
        System.out.println("Nullpointer Exception "+e);
         //  e.printStackTrace();
     }
    catch (IOException e) 
    {
        e.printStackTrace();
    }
    catch (Exception e) 
    {
        e.printStackTrace();
   }

}
Step 2 take backup Contacts

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;

public class VCardActivity extends Activity 
{
Cursor cursor;
ArrayList<String> vCard ;
String vfile;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    vfile = "Contacts" + "_" + System.currentTimeMillis()+".vcf";
    /**This Function For Vcard And here i take one Array List in Which i store every Vcard String of Every Conatact
     * Here i take one Cursor and this cursor is not null and its count>0 than i repeat one loop up to cursor.getcount() means Up to number of phone contacts.
     * And in Every Loop i can make vcard string and store in Array list which i declared as a Global.
     * And in Every Loop i move cursor next and print log in logcat.
     * */
    getVcardString();

}
private void getVcardString() {
    // TODO Auto-generated method stub
    vCard = new ArrayList<String>();
    cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
    if(cursor!=null&&cursor.getCount()>0)
    {
        cursor.moveToFirst();
        for(int i =0;i<cursor.getCount();i++)
        {
            get(cursor);
            Log.d("TAG", "Contact "+(i+1)+"VcF String is"+vCard.get(i));
            cursor.moveToNext();
        }
    }
    else
    {
        Log.d("TAG", "No Contacts in Your Phone");
    }
}

public void get(Cursor cursor)
{

    //cursor.moveToFirst();
    String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
    AssetFileDescriptor fd;
    try {
        fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");

        // Your Complex Code and you used function without loop so how can you get all Contacts Vcard.??


       /* FileInputStream fis = fd.createInputStream();
        byte[] buf = new byte[(int) fd.getDeclaredLength()];
        fis.read(buf);
        String VCard = new String(buf);
        String path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
        FileOutputStream out = new FileOutputStream(path);
        out.write(VCard.toString().getBytes());
        Log.d("Vcard",  VCard);*/

        FileInputStream fis = fd.createInputStream();
        byte[] buf = new byte[(int) fd.getDeclaredLength()];
        fis.read(buf);
        String vcardstring= new String(buf);
        vCard.add(vcardstring);

        String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
        FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, false);
        mFileOutputStream.write(vcardstring.toString().getBytes());

    } catch (Exception e1) 
    {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}
}
This can be help you to take the Contacts as VCF file. For taking sms backup use this method as same for sms backup.

Tuesday, August 25, 2015

android: Bind service using IBinder class

Hello guys, Most of you are aware of the Binding service. You can bind the service with your Activity, Service and Content provider. You can not bind a service with Broadcast receiver.

There are total 3 ways to bind a service with application components

  1. Using IBinder class
  2. Using Messanger class
  3. Using AIDL
This post is for explain about IBinder class 

To implement IBinder class there are following steps

Steps for service
  1. Create a new Project name "BindServiceUsingBinderClass
  2. Create one Service in your application by extending the Service class 
  3. Create a class "LocalBinder" inside your service and extends "Binder" class in this class
  4. Implement the onBind() method of the service and return the instance of the "LocalBinder" class
Steps for activity
  1. Create one activity "Client" and create a instance of the "ServiceConnection" Interface
  2. Implement two methods of this interface onServiceConnectedand onServiceDisconnected
  3. In  onServiceConnected method you will get instance of the iBinder so cast it to LocalBinder class which we have created in the service.
  4. Implement onStart() method and bind the service using bindService()method
  5. Implement onStop() method and unbind the service using unbindService()method
Source code of the IBinder class


Server.java


package com.example.bindservice.binder;

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class Server extends Service{

 IBinder mBinder = new LocalBinder();

 @Override
 public IBinder onBind(Intent intent) {
  return mBinder;
 }

 public class LocalBinder extends Binder {
  public Server getServerInstance() {
   return Server.this;
  }
 }

 public String getTime() {
  SimpleDateFormat mDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  return mDateFormat.format(new Date());
 }
}

Client.java



package com.example.bindservice.binder;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.bindservice.binder.Server.LocalBinder;

public class Client extends Activity {

 boolean mBounded;
 Server mServer;
 TextView text;
 Button button;
 
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        text = (TextView)findViewById(R.id.text);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {
   
   public void onClick(View v) {
    text.setText(mServer.getTime());
   }
  });
    }

 @Override
 protected void onStart() {
  super.onStart();
  Intent mIntent = new Intent(this, Server.class);
        bindService(mIntent, mConnection, BIND_AUTO_CREATE);
 };
 
 ServiceConnection mConnection = new ServiceConnection() {
  
  public void onServiceDisconnected(ComponentName name) {
   Toast.makeText(Client.this, "Service is disconnected", 1000).show();
   mBounded = false;
   mServer = null;
  }
  
  public void onServiceConnected(ComponentName name, IBinder service) {
   Toast.makeText(Client.this, "Service is connected", 1000).show();
   mBounded = true;
   LocalBinder mLocalBinder = (LocalBinder)service;
   mServer = mLocalBinder.getServerInstance();
  }
 };
 
 @Override
 protected void onStop() {
  super.onStop();
  if(mBounded) {
   unbindService(mConnection);
   mBounded = false;
  }
 };
}

android: Get Android phone call history/log programmatically

To get call history programmatically first add read conact permission in Manifest file :

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.WRITE_CALL_LOG" />

Create xml file. Add the below code in xml file :

<Linearlayout android:layout_height="fill_parent"
 android:layout_width="fill_parent"
android:orientation="vertical">

<Textview android:id="@+id/call"
android:layout_height="fill_parent"
android:layout_width="fill_parent">
</Textview>

</Linearlayout>

Now call the getCallDetails() method in java class :

private void getCallDetails() {
StringBuffer sb = new StringBuffer();
Cursor managedCursor = managedQuery( CallLog.Calls.CONTENT_URI,null, null,null, null);
int number = managedCursor.getColumnIndex( CallLog.Calls.NUMBER ); 
int type = managedCursor.getColumnIndex( CallLog.Calls.TYPE );
int date = managedCursor.getColumnIndex( CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex( CallLog.Calls.DURATION);
sb.append( "Call Details :");
while ( managedCursor.moveToNext() ) {
String phNumber = managedCursor.getString( number );
String callType = managedCursor.getString( type );
String callDate = managedCursor.getString( date );
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = managedCursor.getString( duration );
String dir = null;
int dircode = Integer.parseInt( callType );
switch( dircode ) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;

case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;

case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
sb.append( "\nPhone Number:--- "+phNumber +" \nCall Type:--- "+dir+" \nCall Date:--- "+callDayTime+" \nCall duration in sec :--- "+callDuration );
sb.append("\n----------------------------------");
}
managedCursor.close();
call.setText(sb);
}
Using this application user can access his call history. It show call number,call type i.e. incoming/outgoing/missed call, call date-time and call duration. 
Here is the output where user can see all details :



Monday, August 10, 2015

How to Service Running in background in android

1. First create a class  and extends  Service like
 public class MyService extends Service {}
2.Secondly include method in service class like 
@Override
public IBinder onBind(Intent intent) {
    return null;
}
@Override
public void onCreate() {
    super.onCreate();
}
@Override
public void onDestroy() {
    super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// this method keep running service in bacground
return START_STICKY;
}
3.Thirdly include the MyService in manifest   like :
<service
    android:name="MyService"
    android:enabled="true"
    android:label="check Running Apps" />
4.Finally start the service when you want to start like:
startService(new Intent(this, MyService.class)); 
I start service in the following time
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    startService(new Intent(this, MyService.class));
  }
5. When you want to stop the service just use this
stopService(new Intent(this, second_ MyService.class));
6. Fully service class like bellow :
public class second_Service extends Service {
    Timer timer;
    SharedPreferences appData;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

// write  your code , that you want to active  in backgrount in your application .
        return START_STICKY;
    }
}

android:How to detect when an Android app goes to the background and come back to the foreground

app-foreground-background-listen

You can detect when your whole application come to foreground and background using this very simple logic and for all android API level.

Usage

  • You can use with any android API level.
  • Create a BaseActivity for all Activity in your application.
  • You can also use onStart() and onStop() of method of Activty seperately from BaseActivity.
public class BaseActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

public static boolean isAppInFg = false;
public static boolean isScrInFg = false;
public static boolean isChangeScrFg = false;

@Override
protected void onStart() {
    if (!isAppInFg) {
        isAppInFg = true;
        isChangeScrFg = false;
        onAppStart();
    } else {
        isChangeScrFg = true;
    }
    isScrInFg = true;

    super.onStart();
}

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

    if (!isScrInFg || !isChangeScrFg) {
        isAppInFg = false;
        onAppPause();
    }
    isScrInFg = false;
}


public void onAppStart() {
    //remove this toast
    Toast.makeText(getApplicationContext(), "App in foreground", Toast.LENGTH_LONG).show();
    // your code
}

public void onAppPause() {
    //remove this toast
    Toast.makeText(getApplicationContext(), "App in background", Toast.LENGTH_LONG).show();
    // your code
}
}
  • Now use this BaseActivity as a super class of all you Activity like MainActivity extends BaseActivity and onAppStart will be called when you starts your app and onAppPause() will be called when app goes background from any screen.

Tuesday, August 4, 2015

Integrating New Google Admob with Banner and Interstitial ads in Android Studio

This guide will show you how to integrate the Google Mobile Ads SDK into a brand new app and use it to display a simple banner ad. It should take about thirty minutes to complete and will give you a good sense of how the SDK functions within an app. If you're new to Google Mobile Ads, this is a great place to start before moving on to more advanced examples.
The ad unit and samples that we provide return test ads. Test ads are always available, even if your account is suspended or disabled. For more information, review the AdMob policies and learn more about invalid activity.
Using live ads during development is against AdMob policy; if you test on live ads, your AdMob account may be suspended.
No two developers have the same level of experience, so we've added occasional notes like this one for those who are new to Android and Android Studio. If you're an expert, feel free to skip them.

Prerequisites

  • Running Android Studio 1.0 or higher
  • Developing for Android level 9 or higher
In order to complete the Get Started guide, you'll need to have Android Studio installed on your development machine. If you don't already have it, see the Android Studio site for instructions on how to download everything you need to get up and running.
If you haven't used Android Studio before, consider running through the First App Tutorial for Android Studio before starting this one.

Creating a new project

In this step, we'll create a brand new project in Android Studio to use for our example. If you don't already have Studio running, go ahead and open it now.

Start the new project wizard

If you see the above welcome screen, select New Project. Otherwise, select File > New Project from the menu. This will bring up the new project wizard:

Name your project

Enter "BannerExample" as the app name, and whatever company domain you use for your apps. Android Studio will automatically determine a good project location, but feel free to change it if you'd like.

Set the required SDK version

On the next screen, select Phone and Tablet for the form factor and a minimum platform SDK version of 9. That's the minimum version supported by the Google Mobile Ads SDK.

Add your main activity

We're keeping it simple for this example, so on this screen select Blank Activity.

Name your activity

On this screen you have the option of choosing names for the app's activity and its related resources. We'll use the default names for this example, so just click the Finish button.

Compile your new project

After clicking Finish, you'll have a working project with a single activity. Try compiling and running it (select Run 'app' from the Run menu). You should see a "Hello world!" message on an otherwise empty gray screen. Don't worry, we'll add some more content in the next steps.
If you're new to developing Android apps, take a look at the tutorials for USB Debugging and Using Virtual Devices. You'll need to do one of those two things in order to run your new app and see what it looks like.

Download the Google Repository



The Google Repository contains gradle artifacts for the Google Mobile Ads SDK, which your app can use to request and display ads. Make sure that you have the latest version by opening up your SDK Manager. You can do this by selecting Tools > Android > SDK Manager.

The SDK Manager

In the Android SDK Manager window, select Google Repository under the Extras folder, then press Install Packages and accept the licenses to download. If the Install Packages button is disabled, don't worry. That just means you already have the latest version, so there's nothing else you need to do in the SDK Manager.

Configuring gradle



Now that the Google Repository is installed, you need to update your app to reference the Google Play Services SDK inside it. You can do this by adding a line to the dependencies in your app-level build.gradle file. Look for it in the BannerExample/app/ folder and open it.

build.gradle

...
dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        compile 'com.android.support:appcompat-v7:22.2.0'
        compile 'com.google.android.gms:play-services-ads:7.5.0'
    }
...
Update the dependencies section to include the latest Google Play services SDK.
You may see a warning message across the top of the Android Studio window indicating that gradle needs to perform a gradle sync. If that's the case, click Sync Now to do so. Gradle will refresh your project's libraries to include the dependency you just added.
Try rebuilding your project (Run 'app' in the Run menu) to make sure everything compiles correctly. You won't see any changes, but including Google Play services is the first step toward getting ads into your app.

Modify the manifest file

Every Android app uses a file called a manifest to inform the Android system about itself. The information typically found in these files includes things like the permissions required by the app, the activities it contains, and so on. For more details on manifests and how they work, check out the App Manifest Intro.
Now that you have a working app that includes Google Play services, it's time to modify the app manifest file to include the permissions, version number, and activity definition that the Mobile Ads SDK requires. OpenBannerExample/app/src/main/AndroidManifest.xml for editing.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.google.android.gms.example.bannerexample" >

    <!-- Include required permissions for Google Mobile Ads to run-->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <!--This meta-data tag is required to use Google Play Services.-->
        <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>
        <!--Include the AdActivity configChanges and theme. -->
        <activity android:name="com.google.android.gms.ads.AdActivity"
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
            android:theme="@android:style/Theme.Translucent" />
    </application>
</manifest>
There are three changes you need to make:
  1. Add two <uses-permission> tags for INTERNET and ACCESS_NETWORK_STATE. The tag forINTERNET is required and used to access the Internet to make ad requests. ACCESS_NETWORK_STATE is optional, and used to check if an internet connection is available prior to making an ad request.
  2. Add a <meta-data> tag that references the Google Play services version. This lets Android know which version of the service your app expects to use.
  3. Add an <activity> element with configChanges and theme attributes. This activity is used by the SDK when banners are clicked or interstitials are presented, and like any other activity must be declared in the manifest before being presented.
Go ahead and rebuild the project to make sure everything has been done correctly. You should still see the same "Hello world!" message for now. By configuring the App Manifest correctly, though, you've given your app the ability to use Mobile Ads.

Give your app an Ad Unit ID

An Ad Unit ID is a unique identifier given to the places in your app where ads are displayed. If you had an app with two activities, for example, each displaying a banner, you'd have two ad units, each with its own ID. AdMob ad unit IDs have the form ca-app-pub-XXXXXXXXXXXXXXXX/NNNNNNNNNN
In order for your new app to display an ad, it needs to include an Ad Unit ID. Open your app's string resource file, which is found at BannerExample/app/src/main/res/values/strings.xml.

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">My Application</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>
    <string name="banner_ad_unit_id">ca-app-pub-3940256099942544/6300978111</string>
</resources>
Add a new <string> tag as shown. Note that the Ad Unit ID provided above is just for testing. It will allow you to retrieve a sample banner ad and make sure your implementation is correct. You should always use test ads when developing and testing your app--testing with live production ads is a violation of AdMob policy and could cause your account to be suspended. See the addTestDevice method documentation for information on how to get test ads with your own Ad Unit IDs.
While it's not a requirement, storing your Ad Unit ID values in a resource file is a good practice. As your app grows and your ad publishing needs mature, you will occasionally find that you want to change the ID values. If you make sure they're always in a resource file, you'll never have to search through your code looking for them.

Place an AdView in your main activity layout

Layout files contain XML definitions for the visual design of things like activities, fragments, and list items. In this step, we'll be modifying the layout file for the main activity so that it includes an AdView at the bottom. You can add things to an activity progammatically via Java code, but layout files offer better separation of presentation and behavior.
There are only two steps remaining before your app is ready to show an ad. First, you'll need to modify your main activity's layout to include an AdView. OpenBannerExample/app/src/main/res/layout/activity_main.xml in the editor.

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <TextView android:text="@string/hello_world" android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <com.google.android.gms.ads.AdView
        android:id="@+id/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">
    </com.google.android.gms.ads.AdView>
</RelativeLayout>
Add these to the XML:
  1. An additional namespace used for ads:
    http://schemas.android.com/apk/res-auto
    
  2. A new element for your AdView. You'll be asked to provide layout_width and layout_height. You can set both to wrap_content. In the AdView tag, set the adSize to BANNER and the adUnitId to@string/banner_ad_unit_id.
If you look at the last parameter in the AdView tag, you'll see that it's called adUnitId. This is the Ad Unit ID that the AdView will use when requesting ads. In this case, we've given it a reference to the string resource you added in the last step, so the AdView will use that value.

Load the ad in the MainActivity class

The last change needed is for you to add to your app's main activity class some Java code that will load an ad into the AdView.
Open your MainActivity.java file. It will be in the BannerExample/app/src/main/java/ folder, though the exact subdirectory path will vary based on the domain you used when creating your project above. Once it's open in the editor, look for the onCreate method in the MainActivity class:

MainActivity.java (excerpt)

package ...
import ...
import ...
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
public class MainActivity extends ActionBarActivity {

    ...

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

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

    ...
}
Make these two changes:
  1. Import the AdRequest and AdView classes.
  2. Add the code that will find your AdView in the layout, create an AdRequest, and then load an ad into theAdView with it.
Do not use the AdRequest line shown above if you are testing. Refer to our Targeting page to learn more about using test devices and test device IDs.
Once that's completed, you're finished. You now have a fully functional AdView in your app's main activity.

Enjoy a freshly loaded ad

Your app is now ready to display an ad using the Google Mobile Ads SDK. Run it again, and you should see a test banner displayed at the bottom of the device screen:
Congratulations! You've successfully integrated banner ads into an app.