Home Java javaTutorial How Android uses GPS to obtain the user's geographical location and monitor location changes

How Android uses GPS to obtain the user's geographical location and monitor location changes

Jan 07, 2017 pm 03:13 PM

The example in this article describes how Android uses GPS to obtain the user's geographical location and monitor location changes. Share it with everyone for your reference, the details are as follows:

LocationActivity.java

/* LocationActivity.java
 * @author octobershiner
 * 2011 7 22
 * SE.HIT
 * 一个演示定位用户的位置并且监听位置变化的代码
 * */
package uni.location;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.widget.TextView;
public class LocationActivity extends Activity {
 /** Called when the activity is first created. */
 //创建lcoationManager对象
 private LocationManager manager;
 private static final String TAG = "LOCATION DEMO";
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  //获取系统的服务,
  manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
  Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
  //第一次获得设备的位置
  updateLocation(location);
  //重要函数,监听数据测试
  manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 10,
   locationListener);
 }
 /*此处更新一下,当activity不处于活动状态时取消GPS的监听*/
  public void onPause(){
  super.onPause();
  locationManager.removeListener(locationListener);
 }
 //创建一个事件监听器
 private final LocationListener locationListener = new LocationListener() {
   public void onLocationChanged(Location location) {
   updateLocation(location);
   }
   public void onProviderDisabled(String provider){
    updateLocation(null);
    Log.i(TAG, "Provider now is disabled..");
   }
   public void onProviderEnabled(String provider){
    Log.i(TAG, "Provider now is enabled..");
   }
   public void onStatusChanged(String provider, int status,Bundle extras){ }
 };
//获取用户位置的函数,利用Log显示
 private void updateLocation(Location location) {
   String latLng;
   if (location != null) {
   double lat = location.getLatitude();
   double lng = location.getLongitude();
   latLng = "Latitude:" + lat + " Longitude:" + lng;
   } else {
   latLng = "Can't access your location";
   }
   Log.i(TAG, "The location has changed..");
   Log.i(TAG, "Your Location:" +latLng);
 }
}
Copy after login

It is not enough to just modify the activity file. Because of the security of the android system, an authorization mechanism is used for services, so it is necessary Modify the manifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="uni.location"
  android:versionCode="1"
  android:versionName="1.0">
 <uses-sdk android:minSdkVersion="8" />
 <application android:icon="@drawable/icon" android:label="@string/app_name"> 
  <activity android:name=".LocationActivity"
     android:label="@string/app_name">
   <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>
 </application>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
</manifest>
Copy after login

Many friends may have questions, that is, the debugging problem of GPS positioning on the android virtual machine. In fact, it can be simulated. You start the virtual machine, and then open the DDMS interface. Left The side device column will dynamically display the startup status of various services on the virtual machine. After the virtual machine is now unlocked, go to the emulator line under the stand-alone device column. At this time, you will find that there is a location control under the emulator control below. Open it. manual tag, haha ​​I believe you have seen the latitude and longitude, you can change it. Run your program, and then click the send button with the latitude and longitude you just set to simulate receiving the new geographical location.

How Android uses GPS to obtain the users geographical location and monitor location changes

In this demo, I used Log to display the status. It is recommended to use this method. It is very useful. Friends who want to know more can refer to my other article. To learn how to use Log skillfully, I recommend you to search for sundyzlh’s instructional videos.

Regarding the use of LOG, please refer to the previous article "Detailed explanation of Android programming based on Log to demonstrate an activity life cycle instance"

The final effect is as shown in the figure below:

How Android uses GPS to obtain the users geographical location and monitor location changes

I hope this article will be helpful to everyone in Android programming.

For more related articles on how Android uses GPS to obtain the user's geographical location and monitor location changes, please pay attention to the PHP Chinese website!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does Java's classloading mechanism work, including different classloaders and their delegation models? How does Java's classloading mechanism work, including different classloaders and their delegation models? Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

See all articles