search
HomeJavajavaTutorialUsage examples of GPS positioning in Android

GPS positioning is a function that many mobile phones currently have, and it is very practical. This article describes the usage of GPS positioning in Android with examples. Share it with everyone for your reference. The specific method is as follows:

Generally, to obtain the current location through GPS in Android, you must first obtain a LocationManager instance, and obtain the first location through the getLastKnownLocation() method of the instance. The description of this method is as follows:

void android.location.LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

provider is the positioning method, which can use GPS positioning (LocationManager.GPS_PROVIDER) or network positioning (LocationManager.NETWORK_PROVIDER). This article is about GPS positioning, so LocationManager.GPS_PROVIDER is used. minTime is the interval between location updates. Listener is a listener for location changes. Define a LocationListener() yourself, override onLocationChanged(), and add actions when the location changes.

The layout file is as follows:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:orientation="vertical"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  tools:context=".MainActivity" >
  
  <TextView
    android:id="@+id/txt_time"
    style="@style/my_text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="时间:" />
  
  <TextView
    android:id="@+id/txt_lat"
    style="@style/my_text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="经度:" />
  
  <TextView
    android:id="@+id/txt_lng"
    style="@style/my_text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="纬度:" />
  
</LinearLayout>

MainActivity.java file is as follows:

package com.hzhi.my_gps;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
    
  TextView txt_time;
  TextView txt_lat;
  TextView txt_lng;
  LocationManager lom;
  Location loc;
  Double lat;
  Double lng;
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  Date now;
  String str_date;
  Timer timer;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
      
    get_con();
    get_gps();
      
    timer = new Timer(true);
    timer.schedule(task, 0, 1000);
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }
    
  public void get_gps(){
      
    lom = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    loc = lom.getLastKnownLocation(LocationManager.GPS_PROVIDER);
      
    if (loc != null) {
      lat = loc.getLatitude();
      lng = loc.getLongitude();
      txt_lat.setText("纬度:" + String.valueOf(lat));
      txt_lng.setText("经度:" + String.valueOf(lng));
    }
    else{
      txt_lat.setText("纬度:未知" );
      txt_lng.setText("经度:未知" );
    }
      
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    String provider = lom.getBestProvider(criteria, true);
      
    lom.requestLocationUpdates(provider, 1000, 10, los);
  }
    
  LocationListener los = new LocationListener(){
    public void onLocationChanged(Location location){
      if (location != null) {
        lat = location.getLatitude();
        lng = location.getLongitude();
        txt_lat.setText("纬度:" + String.valueOf(lat));
        txt_lng.setText("经度:" + String.valueOf(lng));
      }
      else{
        txt_lat.setText("纬度:未知" );
        txt_lng.setText("经度:未知" );
      }
    };
      
    public void onProviderDisabled(String provider){
      
    };
      
    public void onProviderEnabled(String provider){ };
      
    public void onStatusChanged(String provider, int status,
    Bundle extras){ };
  };
    
  // 获取控件
  public void get_con(){
      
    txt_time = (TextView) findViewById(R.id.txt_time);
    txt_lat = (TextView) findViewById(R.id.txt_lat);
    txt_lng = (TextView) findViewById(R.id.txt_lng);
  }
    
  Handler handler = new Handler(){
      
    public void handleMessage(Message msg){
      switch (msg.what){
      case 1:
        get_time();
        break;
      }
    }
  };
    
  TimerTask task = new TimerTask(){ 
     public void run() { 
       Message message = new Message();   
       message.what = 1;   
       handler.sendMessage(message);  
    } 
  };
    
  // 获取时间
  public void get_time(){
      
    now = new Date(System.currentTimeMillis());
    str_date = formatter.format(now);
    txt_time.setText("时间:" + str_date);
  }
}

Add permissions to the AndroidManifest.xml file:

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

Turn on the GPS satellite before running. The running result is as shown in the figure below:

Usage examples of GPS positioning in Android

Readers can try it outdoors where there is sufficient signal. It is possible. Get GPS location.

I hope this article will be helpful to everyone’s Android programming design.

For more related articles on usage examples of GPS positioning in Android, please pay attention to the PHP Chinese website!


Statement
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
Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteTop 4 JavaScript Frameworks in 2025: React, Angular, Vue, SvelteMar 07, 2025 pm 06:09 PM

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

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

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedSpring Boot SnakeYAML 2.0 CVE-2022-1471 Issue FixedMar 07, 2025 pm 05:52 PM

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

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

Node.js 20: Key Performance Boosts and New FeaturesNode.js 20: Key Performance Boosts and New FeaturesMar 07, 2025 pm 06:12 PM

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

Iceberg: The Future of Data Lake TablesIceberg: The Future of Data Lake TablesMar 07, 2025 pm 06:31 PM

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

How can I implement functional programming techniques in Java?How can I implement functional programming techniques in Java?Mar 11, 2025 pm 05:51 PM

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

How to Share Data Between Steps in CucumberHow to Share Data Between Steps in CucumberMar 07, 2025 pm 05:55 PM

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive

See all articles

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft