Android Location Based Services 1.pdf

Embed Size (px)

Citation preview

  • 7/25/2019 Android Location Based Services 1.pdf

    1/26

    Android Basics

    Android - Home

    Android - Overview

    Android - Environment Setup

    Android - Architecture

    Android - Application Components

    Android - Hello World Example

    Android - Resources

    Android - Activities

    Android - Services

    Android - Broadcast Receivers

    Android - Content Providers

    Android - Fragments

    http://www.tutorialspoint.com/android/android_acitivities.htmhttp://www.tutorialspoint.com/android/android_resources.htmhttp://www.tutorialspoint.com/android/android_hello_world_example.htmhttp://www.tutorialspoint.com/android/android_architecture.htmhttp://www.tutorialspoint.com/android/android_environment_setup.htmhttp://www.tutorialspoint.com/android/android_overview.htmhttp://www.tutorialspoint.com/android/android_fragments.htmhttp://www.tutorialspoint.com/android/android_content_providers.htmhttp://www.tutorialspoint.com/android/android_broadcast_receivers.htmhttp://www.tutorialspoint.com/android/android_services.htmhttp://www.tutorialspoint.com/android/android_acitivities.htmhttp://www.tutorialspoint.com/android/android_resources.htmhttp://www.tutorialspoint.com/android/android_hello_world_example.htmhttp://www.tutorialspoint.com/android/android_application_components.htmhttp://www.tutorialspoint.com/android/android_architecture.htmhttp://www.tutorialspoint.com/android/android_environment_setup.htmhttp://www.tutorialspoint.com/android/android_overview.htmhttp://www.tutorialspoint.com/android/index.htm
  • 7/25/2019 Android Location Based Services 1.pdf

    2/26

    Android - Intents/Filters

    Android - User Interface

    Android - UI Layouts

    Android - UI Controls

    Android - Event Handling

    Android - Styles and Themes

    Android - Custom Components

    Android Advanced Concepts

    Android - Drag and Drop

    Android - Notifications

    Location Based Services

    Android - Sending Email

    Android - Sending SMS

    Android - Phone Calls

    Publishing Android Application

    http://www.tutorialspoint.com/android/android_publishing_application.htmhttp://www.tutorialspoint.com/android/android_phone_calls.htmhttp://www.tutorialspoint.com/android/android_sending_sms.htmhttp://www.tutorialspoint.com/android/android_sending_email.htmhttp://www.tutorialspoint.com/android/android_location_based_services.htmhttp://www.tutorialspoint.com/android/android_notifications.htmhttp://www.tutorialspoint.com/android/android_drag_and_drop.htmhttp://www.tutorialspoint.com/android/android_custom_components.htmhttp://www.tutorialspoint.com/android/android_styles_and_themes.htmhttp://www.tutorialspoint.com/android/android_event_handling.htmhttp://www.tutorialspoint.com/android/android_user_interface_controls.htmhttp://www.tutorialspoint.com/android/android_user_interface_layouts.htmhttp://www.tutorialspoint.com/android/android_intents_filters.htm
  • 7/25/2019 Android Location Based Services 1.pdf

    3/26

    Android Useful Examples

    Android - Alert Dialoges

    Android - Animations

    Android - Audio Capture

    Android - AudioManager

    Android - Auto Complete

    Android - Best Practices

    Android - Bluetooth

    Android - Camera

    Android - Clipboard

    Android - Custom Fonts

    Android - Data Backup

    Android - Developer Tools

    Android - Emulator

    Android - Facebook Integration

    Android - Gestures

    http://www.tutorialspoint.com/android/android_gestures.htmhttp://www.tutorialspoint.com/android/android_facebook_integration.htmhttp://www.tutorialspoint.com/android/android_emulator.htmhttp://www.tutorialspoint.com/android/android_developer_tools.htmhttp://www.tutorialspoint.com/android/android_data_backup.htmhttp://www.tutorialspoint.com/android/android_custom_fonts.htmhttp://www.tutorialspoint.com/android/android_clipboard.htmhttp://www.tutorialspoint.com/android/android_camera.htmhttp://www.tutorialspoint.com/android/android_bluetooth.htmhttp://www.tutorialspoint.com/android/android_best_practices.htmhttp://www.tutorialspoint.com/android/android_auto_complete.htmhttp://www.tutorialspoint.com/android/android_audiomanager.htmhttp://www.tutorialspoint.com/android/android_audio_capture.htmhttp://www.tutorialspoint.com/android/android_animations.htmhttp://www.tutorialspoint.com/android/android_alert_dialoges.htm
  • 7/25/2019 Android Location Based Services 1.pdf

    4/26

    Android - Google Maps

    Android - Image Effects

    Android - ImageSwitcher

    Android - Internal Storage

    Android - JetPlayer

    Android - JSON Parser

    Android - Linkedin Integration

    Android - Loading Spinner

    Android - Localization

    Android - Login Screen

    Android - MediaPlayer

    Android - Multitouch

    Android - Navigation

    Android - Network Connection

    Android - NFC Guide

    Android - PHP/MySQL

    http://www.tutorialspoint.com/android/android_php_mysql.htmhttp://www.tutorialspoint.com/android/android_nfc_guide.htmhttp://www.tutorialspoint.com/android/android_network_connection.htmhttp://www.tutorialspoint.com/android/android_navigation.htmhttp://www.tutorialspoint.com/android/android_multitouch.htmhttp://www.tutorialspoint.com/android/android_mediaplayer.htmhttp://www.tutorialspoint.com/android/android_login_screen.htmhttp://www.tutorialspoint.com/android/android_localization.htmhttp://www.tutorialspoint.com/android/android_loading_spinner.htmhttp://www.tutorialspoint.com/android/android_linkedin_integration.htmhttp://www.tutorialspoint.com/android/android_json_parser.htmhttp://www.tutorialspoint.com/android/android_jetplayer.htmhttp://www.tutorialspoint.com/android/android_internal_storage.htmhttp://www.tutorialspoint.com/android/android_imageswitcher.htmhttp://www.tutorialspoint.com/android/android_image_effects.htmhttp://www.tutorialspoint.com/android/android_google_maps.htm
  • 7/25/2019 Android Location Based Services 1.pdf

    5/26

    Android - Progress Circle

    Android - ProgressBar

    Android - Push Notification

    Android - RenderScript

    Android - RSS Reader

    Android - Screen Cast

    Android - SDK Manager

    Android - Sensors

    Android - Session Management

    Android - Shared Preferences

    Android - SIP Protocol

    Android - Spelling Checker

    Android - SQLite Database

    Android - Support Library

    Android - Testing

    Android - Text to Speech

    http://www.tutorialspoint.com/android/android_text_to_speech.htmhttp://www.tutorialspoint.com/android/android_testing.htmhttp://www.tutorialspoint.com/android/android_support_library.htmhttp://www.tutorialspoint.com/android/android_sqlite_database.htmhttp://www.tutorialspoint.com/android/android_spelling_checker.htmhttp://www.tutorialspoint.com/android/android_sip_protocol.htmhttp://www.tutorialspoint.com/android/android_shared_preferences.htmhttp://www.tutorialspoint.com/android/android_session_management.htmhttp://www.tutorialspoint.com/android/android_sensors.htmhttp://www.tutorialspoint.com/android/android_sdk_manager.htmhttp://www.tutorialspoint.com/android/android_screen_cast.htmhttp://www.tutorialspoint.com/android/android_rss_reader.htmhttp://www.tutorialspoint.com/android/android_renderscript.htmhttp://www.tutorialspoint.com/android/android_push_notification.htmhttp://www.tutorialspoint.com/android/android_progressbar.htmhttp://www.tutorialspoint.com/android/android_progress_circle.htm
  • 7/25/2019 Android Location Based Services 1.pdf

    6/26

    Android - TextureView

    Android - Twitter Integration

    Android - UI Design

    Android - UI Patterns

    Android - UI Testing

    Android - WebView Layout

    Android - Wi-Fi

    Android - Widgets

    Android - XML Parsers

    Android Useful Resources

    Android - Questions and Answers

    Android - Useful Resources

    Android - Discussion

    Android - Location Based Services

    http://www.tutorialspoint.com/android/android_discussion.htmhttp://www.tutorialspoint.com/android/android_useful_resources.htmhttp://www.tutorialspoint.com/android/android_questions_answers.htmhttp://www.tutorialspoint.com/android/android_xml_parsers.htmhttp://www.tutorialspoint.com/android/android_widgets.htmhttp://www.tutorialspoint.com/android/android_wi_fi.htmhttp://www.tutorialspoint.com/android/android_webview_layout.htmhttp://www.tutorialspoint.com/android/android_ui_testing.htmhttp://www.tutorialspoint.com/android/android_ui_patterns.htmhttp://www.tutorialspoint.com/android/android_ui_design.htmhttp://www.tutorialspoint.com/android/android_twitter_integration.htmhttp://www.tutorialspoint.com/android/android_textureview.htm
  • 7/25/2019 Android Location Based Services 1.pdf

    7/26

    Previous Page Next Page

    Android location APIs make it easy for you to build location-aware applications, without needing to focus on thedetails of the underlying location technology.

    This becomes possible with the help of Google Play services, which facilitates adding location awareness to your app wi

    automated location tracking, geofencing, and activity recognition.

    This tutorial shows you how to use Location Services in your APP to get the current location, get periodic location updates, look

    addresses etc.

    The Locationobject represents a geographic location which can consist of a latitude, longitude, time stamp, and other informati

    such as bearing, altitude and velocity. There are following important methods which you can use with Location object to g

    location specific information:

    The Location Object

    http://www.tutorialspoint.com/android/android_sending_email.htmhttp://www.tutorialspoint.com/android/android_notifications.htm
  • 7/25/2019 Android Location Based Services 1.pdf

    8/26

    Sr.No. Method & Description

    1 float distanceTo(Location dest)

    Returns the approximate distance in meters between this location and the given location.

    2 float getAccuracy()

    Get the estimated accuracy of this location, in meters.

    3 double getAltitude()

    Get the altitude if available, in meters above sea level.

    4 float getBearing()

    Get the bearing, in degrees.

    5 double getLatitude()Get the latitude, in degrees.

    6 double getLongitude()

    Get the longitude, in degrees.

    7 float getSpeed()

    Get the speed if it is available, in meters/second over ground.

    8 boolean hasAccuracy()

    True if this location has an accuracy.

    9 boolean hasAltitude()

    True if this location has an altitude.

  • 7/25/2019 Android Location Based Services 1.pdf

    9/26

    10 boolean hasBearing()

    True if this location has a bearing.

    11 boolean hasSpeed()

    True if this location has a speed.

    12 void reset()

    Clears the contents of the location.

    13 void setAccuracy(float accuracy)

    Set the estimated accuracy of this location, meters.

    14 void setAltitude(double altitude)

    Set the altitude, in meters above sea level.

    15 void setBearing(float bearing)

    Set the bearing, in degrees.

    16 void setLatitude(double latitude)

    Set the latitude, in degrees.

    17 void setLongitude(double longitude)

    Set the longitude, in degrees.

    18 void setSpeed(float speed)

    Set the speed, in meters/second over ground.

  • 7/25/2019 Android Location Based Services 1.pdf

    10/26

    19 String toString()

    Returns a string containing a concise, human-readable description of this object.

    To get the current location, create a location client which is LocationClientobject, connect it to Location Services using connec

    method, and then call its getLastLocation()method. This method returns the most recent location in the form of Locationobje

    that contains latitude and longitude coordinates and other information as explained above. To have location based functionality

    your activity, you will have to implement two interfaces

    GooglePlayServicesClient.ConnectionCallbacks

    GooglePlayServicesClient.OnConnectionFailedListener

    These interfaces provide following important callback methods, which you need to implement in your activity class

    Sr.No. Callback Methods & Description

    1 abstract void onConnected(Bundle connectionHint)

    This callback method is called when location service is connected to the location client successfully. You will us

    connect()method to connect to the location client.

    2 abstract void onDisconnected()

    This callback method is called when the client is disconnected. You will use disconnect()method to disconnect frothe location client.

    3 abstract void onConnectionFailed(ConnectionResult result)

    This callback method is called when there was an error connecting the client to the service.

    Get the Current Location

  • 7/25/2019 Android Location Based Services 1.pdf

    11/26

    You should create the location client in onCreate()method of your activity class, then connect it in onStart(), so that Location

    Services maintains the current location while your activity is fully visible. You should disconnect the client in onStop()method,

    so that when your app is not visible, Location Services is not maintaining the current location. This helps in saving battery

    power up-to a large extent.

    If you are willing to have location updates, then apart from above mentioned interfaces, you will need to impleme

    LocationListenerinterface as well. This interface provide following callback method, which you need to implement in your activi

    class

    Sr.No. Callback Method & Description

    1 abstract void onLocationChanged(Location location)

    This callback method is used for receiving notifications from the LocationClient when the location has changed.

    The LocationRequestobject is used to request a quality of service (QoS) for location updates from the LocationClient. There a

    following useful setter methods which you can use to handle QoS. There are equivalent getter methods available which you c

    check in Android official documentation.

    Sr.No. Method & Description

    1 setExpirationDuration(long millis)

    Set the duration of this request, in milliseconds.

    2 setExpirationTime(long millis)

    Set the request expiration time, in millisecond since boot.

    Get the Updated Location

    Location Quality of Service

  • 7/25/2019 Android Location Based Services 1.pdf

    12/26

    3 setFastestInterval(long millis)

    Explicitly set the fastest interval for location updates, in milliseconds.

    4 setInterval(long millis)

    Set the desired interval for active location updates, in milliseconds.

    5 setNumUpdates(int numUpdates)

    Set the number of location updates.

    6 setPriority(int priority)

    Set the priority of the request.

    Now for example, if your application wants high accuracy location it should create a location request with setPriority(int) setPRIORITY_HIGH_ACCURACY and setInterval(long) to 5 seconds. You can also use bigger interval and/or other priorities li

    PRIORITY_LOW_POWER for to request "city" level accuracy or PRIORITY_BALANCED_POWER_ACCURACY for "block" lev

    accuracy.

    Activities should strongly consider removing all location request when entering the background (for example at onPause()), or

    at least swap the request to a larger interval and lower quality to save power consumption.

    Once you have Location object, you can use Geocoder.getFromLocation() method to get an address for a given latitude a

    longitude. This method is synchronous, and may take a long time to do its work, so you should call the method from t

    doInBackground()method of an AsyncTaskclass.

    The AsyncTaskmust be subclassed to be used and the subclass will override doInBackground(Params...)method to perform

    Displaying a Location Address

  • 7/25/2019 Android Location Based Services 1.pdf

    13/26

    task in the background and onPostExecute(Result)method is invoked on the UI thread after the background computation finish

    and at the time to display the result. There is one more important method available in AyncTask which is execute(Params

    params), this method executes the task with the specified parameters.

    Check following example to have better understanding on how we use AynchTask in any Android application to get work done

    the background without interfering main task.

    Following example shows you in practical how to to use Location Services in your app to get the current location and its equivale

    addresses etc.

    To experiment with this example, you will need actual Mobile device equipped with latest Android OS, otherwise you will have

    to struggle with emulator which may not work.

    Before you proceed to have location support in your Android Applications, you need to set-up Google Play Services SDK usi

    following simple steps

    Steps Description

    1 Launch Android Studio IDE

    From Android Studio select file >project structure >dependencies > Click on + button to add dependencies

    you would get choose library dependencies dialog window

    2 Search for com.google.android.gms:play-services:6.5.87or higher version library. its depend on which android version is using

    with.

    3 Select the google play services and press apply button as shown below image

    Example

    Install the Google Play Services SDK

  • 7/25/2019 Android Location Based Services 1.pdf

    14/26

    Step Description

    1 You will use Android studio IDE to create an Android application and name it as Tutorialspointunder a package

    com.example.Tutorialspoint. While creating this project, make sure you Target SDKand Compile Withat the latest version of Android

    SDK to use higher levels of APIs.

    2 Add Google Play Servicelibrary in your project by following simple steps given below.

    3 Modify src/MainActivity.javafile and add required code as shown below to take care of getting current location and its equivalent

    address.

    4 Modify layout XML file res/layout/activity_main.xmlto add all GUI components which include three buttons and two text views to

    show location/address.

    5 Modify res/values/strings.xmlto define required constant values

    6 ModifyAndroidManifest.xmlas shown below

    7 Run the application to launch Android emulator and verify the result of the changes done in the application.

    Let's add Google Play Service reference in the project.Click on file > project structure > dependencies >and select + and th

    search google play services which will show com.google.android.gms:play-services:6.5.87Click on ok button. it will close the choo

    dependencies windows. you must be close project structure by clicking apply button

    Create Android Application

  • 7/25/2019 Android Location Based Services 1.pdf

    15/26

    Above image is showing the result of adding google play services to project. after add google play services to project. It should

    as follows

  • 7/25/2019 Android Location Based Services 1.pdf

    16/26

    Following is the content of the modified main activity file src/com.example.Tutorialspoint/MainActivity.java.

    packagecom.example.Tutorialspoint;

    importjava.io.IOException;

  • 7/25/2019 Android Location Based Services 1.pdf

    17/26

    importjava.util.List;

    importjava.util.Locale;

    importcom.google.android.gms.common.ConnectionResult;

    importcom.google.android.gms.common.GooglePlayServicesClient ;

    importcom.google.android.gms.location.LocationClient;

    importandroid.content.Context;

    importandroid.location.Address;

    importandroid.location.Geocoder;

    importandroid.location.Location;

    importandroid.os.AsyncTask;

    importandroid.os.Bundle;

    importandroid.support.v4.app.FragmentActivity;

    importandroid.util.Log;

    importandroid.view.View;

    importandroid.widget.Button;

    importandroid.widget.TextView;

    importandroid.widget.Toast;

    publicclassMainActivityextendsFragmentActivityimplements

    GooglePlayServicesClient .ConnectionCallbacks,

    GooglePlayServicesClient .OnConnectionFailedListener

    {

    LocationClientmLocationClient;

    privateTextViewaddressLabel;

    privateTextViewlocationLabel;

    privateButtongetLocationBtn;

    privateButtondisconnectBtn;

    privateButtonconnectBtn;

    @Override

    protectedvoidonCreate(BundlesavedInstanceState){

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    locationLabel =(TextView)findViewById(R.id.locationLabel);

    addressLabel =(TextView)findViewById(R.id.addressLabel);

    getLocationBtn =(Button)findViewById(R.id.getLocation);

  • 7/25/2019 Android Location Based Services 1.pdf

    18/26

    getLocationBtn.setOnClickListener(newView.OnClickListener(){

    publicvoidonClick(Viewview){

    displayCurrentLocation ();

    }

    });

    disconnectBtn =(Button)findViewById(R.id.disconnect);

    disconnectBtn.setOnClickListener(newView.OnClickListener(){

    publicvoidonClick(Viewview){

    mLocationClient.disconnect();

    locationLabel.setText("Got disconnected....");}

    });

    connectBtn =(Button)findViewById(R.id.connect);

    connectBtn.setOnClickListener(newView.OnClickListener(){

    publicvoidonClick(Viewview){

    mLocationClient.connect();

    locationLabel.setText("Got connected....");

    }

    });

    // Create the LocationRequest objectmLocationClient =newLocationClient(this,this,this);

    }

    @Override

    protectedvoidonStart(){

    super.onStart();

    // Connect the client.

    mLocationClient.connect();

    locationLabel.setText("Got connected....");

    }

    @Override

    protectedvoidonStop(){

    // Disconnect the client.

    mLocationClient.disconnect();

    super.onStop();

    locationLabel.setText("Got disconnected....");

    }

    @Override

  • 7/25/2019 Android Location Based Services 1.pdf

    19/26

    publicvoidonConnected(BundledataBundle){

    // Display the connection status

    Toast.makeText(this,"Connected",Toast.LENGTH_SHORT).show();

    }

    @Override

    publicvoidonDisconnected(){

    // Display the connection status

    Toast.makeText(this,"Disconnected. Please re-connect.",Toast.LENGTH_SHORT).show();

    }

    @Override

    publicvoidonConnectionFailed(ConnectionResultconnectionResult){

    // Display the error code on failure

    Toast.makeText(this,"Connection Failure : "+connectionResult.getErrorCode(),Toast.LENGTH_SHORT).show();

    }

    publicvoid displayCurrentLocation(){

    // Get the current location's latitude & longitude

    LocationcurrentLocation =mLocationClient.getLastLocation();

    Stringmsg ="Current Location: "+

    Double.toString(currentLocation.getLatitude())+","+

    Double.toString(currentLocation.getLongitude());

    // Display the current location in the UI

    locationLabel.setText(msg);

    // To display the current address in the UI

    (newGetAddressTask(this)).execute(currentLocation);

    }

    /*

    * Following is a subclass of AsyncTask which has been used to get

    * address corresponding to the given latitude & longitude.

    */

    privateclassGetAddressTaskextendsAsyncTask{ContextmContext;

    publicGetAddressTask(Contextcontext){

    super();

    mContext =context;

    }

    /*

    * When the task finishes, onPostExecute() displays the address.

    */

  • 7/25/2019 Android Location Based Services 1.pdf

    20/26

    @Override

    protectedvoidonPostExecute(Stringaddress){

    // Display the current address in the UI

    addressLabel.setText(address);

    }

    @Override

    protectedStringdoInBackground(Location...params){

    Geocodergeocoder =newGeocoder(mContext,Locale.getDefault());

    // Get the current location from the input parameter listLocationloc =params[0];

    // Create a list to contain the result address

    addresses =null;

    try{

    addresses =geocoder.getFromLocation(loc.getLatitude(),loc.getLongitude(),1);

    }

    catch(IOExceptione1){

    Log.e("LocationSampleActivity" ,IO ExceptioningetFromLocation());

    e1.printStackTrace();

    return("IO Exception trying to get address");}

    catch(IllegalArgumentException e2){

    // Error message to post in the log

    StringerrorString ="Illegal arguments "+

    Double.toString(loc.getLatitude())+" , "+Double.toString(loc.getLongitude())+" passed to address service"

    Log.e("LocationSampleActivity" ,errorString);

    e2.printStackTrace();

    returnerrorString;

    }

    // If the reverse geocode returned an address

    if(addresses !=null&&addresses.size()>0){// Get the first address

    Addressaddress =addresses.get(0);

    /*

    * Format the first line of address (if available),

    * city, and country name.

    */

    StringaddressText =String.format("%s, %s, %s");

  • 7/25/2019 Android Location Based Services 1.pdf

    21/26

    // If there's a street address, add it

    address.getMaxAddressLineIndex ()>0?

    address.getAddressLine(0):"",

    // Locality is usually a city

    address.getLocality(),

    // The country of the address

    address.getCountryName());

    // Return the textreturnaddressText;

    }

    else{

    return"No address found";

    }

    }

    }// AsyncTask class

    }

    Following will be the content of res/layout/activity_main.xmlfile

  • 7/25/2019 Android Location Based Services 1.pdf

    22/26

    android:layout_alignEnd ="@+id/imageButton" >

    < LinearLayout>

    Following will be the content of res/values/strings.xmlto define two new constants:

    Tutorialspoint< string>

    Settings< string>

    Hello world!< string>

    " l i " G L i

  • 7/25/2019 Android Location Based Services 1.pdf

    23/26

    Get Location< string>

    Disconnect Service< string>

    Connect Service< string>

    < resources>

    Following is the default content of AndroidManifest.xml

    < intent filter>

    < activity>

    < application>

    < manifest>

    Let's try to run your Tutorialspointapplication. I assume that, you have connected your actual Android Mobile device with yocomputer. To run the app from Android Studio, open one of your project's activity files and click Run icon from the toolb

    Before starting your application, Android studio installer will display following window to select an option where you want to r

    your Android application.

  • 7/25/2019 Android Location Based Services 1.pdf

    24/26

    Now to see location select Get Location Button which will display location information as follows

  • 7/25/2019 Android Location Based Services 1.pdf

    25/26

    Previous Page Next Page

    You can try by disconnecting location client using Disconnect Serviceand then connecting it by using Connect Servicebutton. Y

    can also modify to get location update as explained above and in Android Official documentation.

    Advertisements

    http://www.tutorialspoint.com/android/android_sending_email.htmhttp://www.tutorialspoint.com/android/android_notifications.htm
  • 7/25/2019 Android Location Based Services 1.pdf

    26/26

    Write for us FAQ's Helping Contact

    Copyright 2016. All Rights Reserved.

    Enter email for newslet go

    http://www.tutorialspoint.com/about/contact_us.htmhttp://www.tutorialspoint.com/about/about_helping.htmhttp://www.tutorialspoint.com/about/faq.htmhttp://www.tutorialspoint.com/about/tutorials_writing.htm