Wednesday, July 8, 2020
Location based Services in Android Tutorial
Location based Services in Android Tutorial Location Based Services in Android Part 1 Back Home Categories Online Courses Mock Interviews Webinars NEW Community Write for Us Categories Artificial Intelligence AI vs Machine Learning vs Deep LearningMachine Learning AlgorithmsArtificial Intelligence TutorialWhat is Deep LearningDeep Learning TutorialInstall TensorFlowDeep Learning with PythonBackpropagationTensorFlow TutorialConvolutional Neural Network TutorialVIEW ALL BI and Visualization What is TableauTableau TutorialTableau Interview QuestionsWhat is InformaticaInformatica Interview QuestionsPower BI TutorialPower BI Interview QuestionsOLTP vs OLAPQlikView TutorialAdvanced Excel Formulas TutorialVIEW ALL Big Data What is HadoopHadoop ArchitectureHadoop TutorialHadoop Interview QuestionsHadoop EcosystemData Science vs Big Data vs Data AnalyticsWhat is Big DataMapReduce TutorialPig TutorialSpark TutorialSpark Interview QuestionsBig Data TutorialHive TutorialVIEW ALL Blockchain Blockchain TutorialWhat is BlockchainHyperledger FabricWhat Is EthereumEthereum TutorialB lockchain ApplicationsSolidity TutorialBlockchain ProgrammingHow Blockchain WorksVIEW ALL Cloud Computing What is AWSAWS TutorialAWS CertificationAzure Interview QuestionsAzure TutorialWhat Is Cloud ComputingWhat Is SalesforceIoT TutorialSalesforce TutorialSalesforce Interview QuestionsVIEW ALL Cyber Security Cloud SecurityWhat is CryptographyNmap TutorialSQL Injection AttacksHow To Install Kali LinuxHow to become an Ethical Hacker?Footprinting in Ethical HackingNetwork Scanning for Ethical HackingARP SpoofingApplication SecurityVIEW ALL Data Science Python Pandas TutorialWhat is Machine LearningMachine Learning TutorialMachine Learning ProjectsMachine Learning Interview QuestionsWhat Is Data ScienceSAS TutorialR TutorialData Science ProjectsHow to become a data scientistData Science Interview QuestionsData Scientist SalaryVIEW ALL Data Warehousing and ETL What is Data WarehouseDimension Table in Data WarehousingData Warehousing Interview QuestionsData warehouse architectureTalend T utorialTalend ETL ToolTalend Interview QuestionsFact Table and its TypesInformatica TransformationsInformatica TutorialVIEW ALL Databases What is MySQLMySQL Data TypesSQL JoinsSQL Data TypesWhat is MongoDBMongoDB Interview QuestionsMySQL TutorialSQL Interview QuestionsSQL CommandsMySQL Interview QuestionsVIEW ALL DevOps What is DevOpsDevOps vs AgileDevOps ToolsDevOps TutorialHow To Become A DevOps EngineerDevOps Interview QuestionsWhat Is DockerDocker TutorialDocker Interview QuestionsWhat Is ChefWhat Is KubernetesKubernetes TutorialVIEW ALL Front End Web Development What is JavaScript รข" All You Need To Know About JavaScriptJavaScript TutorialJavaScript Interview QuestionsJavaScript FrameworksAngular TutorialAngular Interview QuestionsWhat is REST API?React TutorialReact vs AngularjQuery TutorialNode TutorialReact Interview QuestionsVIEW ALL Mobile Development Android TutorialAndroid Interview QuestionsAndroid ArchitectureAndroid SQLite DatabaseProgramming Part 1 Last updated o n Apr 28,2020 11.6K Views shivani kapahi2 Comments Bookmark Become a Certified Professional I believe if our concepts are clear on a particular topic, it does not take much time to understand how to play around with that concept. So, let us start with the concepts first and then we will deal with the actual code development.Location Based Services In Android The ConceptWe have something known as Location Based Services in Android. Location Based Services are provided by Android through its location framework. The framework provides a location API which consists of certain classes and interface. These classes and interface are the key components which allow us to develop Location Based Application in Android.Classes and Interfaces of Location Based Services:LocationManager This class helps to get access to the location service of the system. LocationListener This interface acts as the listener which receives notification from the location manager when the location changes or th e location provider is disabled or enabled. Location This is the class which represents the geographic location returned at a particular time.These android built-in components have made it easier for us to get the user location. In this blog post, we will walk through the steps that need to be followed to retrieve user location.Step 1An instance of the LocationManager needs to be created as the first step in this process. This is the main class through which the application gets access to the location services in Android. A reference to this system service can be obtained by calling getSystemService() method.LocationManagerlocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);Step 2Next step is to identify the location provider you would like to use for retrieving location details. The location providers actually provide the location data in Android. Android exposes two main location providers:1. GPS Location Provider:This location provider provides location data with the highest accuracy (~2 m 20m). Location updates are provided through satellites. However there are some drawbacks with this provider which are explained as below:A. It is significantly slower than the network provider to get the initial connection setup with the satellites. This initial connection, also called Time to First Fix (TTFF) can be extremely slow but once the connection is established, location updates are quite fast.B. GPS provider also drains out the battery very first. So, it is very important to judiciously use this provider. Special care should be taken to ensure that this is turned off when you are not using it.C. The third draw back comes from the fact that GPS uses radio signal which is obstructed by solid objects. So, GPS provider will not work if you are inside a building or in a basement.2. Network Provider:This provider uses Wi-Fi hotspots and cell tower to approximate a location. The provider retrieves an approximate location by querying the Goog le location server using the IDs of the Wi-Fi hotspots and cell towers. Location accuracy is between 100 1000 m. The location accuracy is directly proportional to the number of Wi-Fi hotspots and cell towers available in the area.You can check the availability of the providers using the below piece of code:isGpsEnabled = mLocManager.isProviderEnabled(LocationManager.GPS_PROVIDER); isNetworkEnabled = mLocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);Step 3The next step is to register a location listener with the location manager. The registration can be done by calling the method requestLocationUpdates((String provider, long minTime, float minDistance, LocationListener listener).Following are the parameters passed to this method:provider: the name of the provider with which to register. This can be either GPS or Network provider.minTime: minimum time interval between location updates, in milliseconds.minDistance: minimum distance between location updates, in meters.lis tener: a LocationListener whose onLocationChanged(Location) method will be called for each location update.The Location Manager calls the onLocationChanged() of the listener when the mobile has moved a distance greater than the minDistance or the time since last location update is more than minTime.Location Based Services In Android The CodeWe just brushed up some basic concepts based on Location Based Services in Android. Let us now learn how to exercise those concepts!1. Prerequisites:One should have the knowledge of how to test location based services in emulator through the emulator; you can setup mock locations through the emulator control. For this, in the emulator control, type the latitude and longitude and hit the SEND button. This will setup the mock location of the emulator.Permissions required for Location Based Services in Android In the Android manifest file, you will need to specify 3 permissions as mentioned below:uses-permissionandroid:name=android.permission.ACC ESS_COARSE_LOCATION/ uses-permissionandroid:name=android.permission.ACCESS_FINE_LOCATION/ uses-permissionandroid:name=android.permission.INTERNET/For GPS based location, you need only the android.permission.ACCESS_FINE_LOCATION For Network based location, you need only the android.permission.ACCESS_FINE_LOCATION If you are using both the providers, you need to request only for the ACCESS_FINE_LOCATION permission, it includes permission for both the providers.2. Layout:It is always easy to understand an application if we start from the layout/user interface of the application project. The layout for this sample application looks as below:It has 4 views:1 This is the label for the latitude. 2 This text view will be populated with the latitude of the location. 3 This is the label for the longitude. 4 This text view will be populated with the longitude of the location. On click of this button the latitude and longitude will be retrieved and populated in their respective text views.3 . The Code:Let us now look at the important snippets of the code:The MainActivity class implements the location listener. This class will be used as the listener and the location manager will register itself to this listener.publicclassMainActivityextends Activity implementsLocationListener, OnClickListener{In the OnCreate() method, I am doing 2 important things:1. Got an instance of the location manager by calling the sodystem service met mLocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);2. Checking which location provider is enabledisGpsEnabled = mLocManager.isProviderEnabled(LocationManager.GPS_PROVIDER); isNetworkEnabled = mLocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);Below is my logic in the OnClick method of the button view. When the button is clicked, I check which provider is enabled. If GPS is enabled, I register the location manager with the location listener (which is this instance of the MainActivity class) using GPS provider, el se I use Network Provider. This part is the key. When the requestLocationUpdates method is called, it in turn will call the onLocationChanged method and will pass the location object to that method./pre @Override publicvoidonClick(View v) { // TODO Auto-generated method stub int id = v.getId(); switch (id) { caseR.id.btGetLocation: if(isGpsEnabled) { mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 10, MainActivity.this); } elseif(isNetworkEnabled) { mLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 10, MainActivity.this); } break; default: break; } What happens in the onLocationChanged() method?/pre latitude = loc.getLatitude(); longitude = loc.getLongitude(); tvLatitude.setText(String.valueOf(latitude)); tvlongitude.setText(String.valueOf(longitude)); mLocManager.removeUpdates(this); I get the latitude and longitude and then unregister the location manager from the listener. This is done to save the battery power of the mobile. If you do not code this, this method will try to access the GPS to get more accurate/precise location details of the mobile. But for our purpose we are content by getting the first location that is retrieved from the satellite.This article introduces you to the concept of using Location Based Services in Android and explains how you can get the latitude and longitude of your mobile location. In the next part, I will explain how you can retrieve address using 0074he latitude and longitude. So, please stay tuned!Have a doubt in the discussed concepts?Ask our experts!Stay tuned for more tutorials to learn how to create Android widgets! Happy Learning!The following resources were used for creating this post:Edureka.in. You may also like these related posts:Understanding Adapters In AndroidAndroid Project : BlackJack GameAndroid Tutorials for Beginners-5: Broadcast ReceiverRecommended videos for you Develop Mobile Apps Using Android Lollipop Watch Now Introduction to Android Development Watch Now Building Native Application In IOS 8 Watch Now Building Application In Android Lollipop Watch Now Android 5.0 Lollipop Watch Now iOS Development-When Android is not enough Watch Now Learn How To Animate Your Android App Watch Now Android Development : Using Android 5.0 Lollipop (4th Feb 15) Watch Now Working with Advanced Views in Android Watch NowRecommended blogs for you Android Services Tutorial : How to run an application in the background? Read Article Introduction to Cursor in Android Read Article Android Project : PNR Status Enquiry Read Article Android Interview Questions And Answers For Beginners In 2020 Read Article Android Development Basics: Students Queries for Introductory Session Read Article Top Android Interview Questions and Answers for Freshers In 2020 Read Article How to Create Android Widgets:Custom Toast Re ad Article Android Interview Questions for Fresher and Experienced In 2020 Read Article Flutter vs React Native Which One You Should Learn? Read Article Android Adapter Tutorial: What Are Adapters in Android Read Article Learn Kotlin Programming Language From Scratch Read Article An ISRO Scientist Underwent Android Online Training! Read Article How To Become An Android Developer? Read Article Android Studio Tutorial One Stop Solution for Beginners Read Article Location Based Services in Android Part 1 Read Article Why iOS and OS X Developers are Choosing Swift Read Article How to Create Android Apps in 5 Simple Steps! Read Article TextView Justification in Android Read Article Android Tutorial Learn Android From Scratch! Read Article How To Work With Kotlin Native? Read Article Comments 2 Comments Trending Courses in Mobile Development Android App Development Certification Trainin ...59k Enrolled LearnersWeekendLive Class Reviews 5 (23250)
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.