search
HomeJavajavaTutorialAndroid opens GPS navigation and obtains location information and returns null solution

I was working on an Android project recently and needed to use GPS to obtain location information. After checking the API, I found that obtaining location information only requires an extremely simple sentence:

getLastKnownLocation(LocationManager.GPS_PROVIDER),

So I was very happy. But as soon as I wrote it into the code, the return value (Location type) was always null... which was very frustrating. After searching on the Internet for a long time, I found that many people are struggling with this problem like me. Some people say it is because the GPS is not turned on, and some people say it is because the relevant permissions are not added. But mine has obviously been turned on in the settings, and the permissions are natural. Also added. After struggling with the API for a long time, I finally found out the reason. It turns out that turning on GPS actually depends on this sentence:

setTestProviderEnabled("gps",true);

and it has nothing to do with the settings on the phone (at least this is what I tested on my phone) . Even if the settings on the phone are turned off, this sentence can still be turned on; and even if the phone settings are turned on, it is useless without this line. Corresponding to this sentence is

setTestProviderEnabled("gps",false);

used to turn off GPS.
Can we use the above method to obtain the Location after GPS is turned on? Still can not! To be precise, sometimes it is possible, because this function obtains the position information obtained last time. Imagine that if this program is run for the first time, the position information has not been obtained before, and of course the return value will be null. After carefully checking the API, I found this sentence in

requestLocationUpdates (String provider, long minTime, float minDistance, LocationListener listener)

: It may take a while to receive the most recent location. If an immediate location is required, applications may use the getLastKnownLocation(String) method. Therefore In order to obtain location information, you should use this method to set a listener for the manager and obtain it in onLocationChanged(Location location) in the listener.
The test code is as follows:

public void onLocationChanged(Location location)
            {
                Log.i("onLocationChanged", "come in");
                if (location != null)
                {
                    Log.w("Location","Current altitude = "+ location.getAltitude()); 
                    Log.w("Location","Current latitude = "+ location.getLatitude());
                }
            }

After testing, the Location can be obtained after a period of time (the acquisition time is related to minTime and minDistance). Another issue that needs attention is that after setting up the listener, you cannot use the above method to turn off GPS before deleting the listener, otherwise an error will be reported. Therefore, the method to turn off gps is

manager.removeUpdates (listener);//listener 即为监听器实例
manager.setTestProviderEnabled("gps",false);

The following is the test code, the required permissions are:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS"></uses-permission>
import android.app.Activity;
 import android.content.Context;
 import android.location.Criteria;
 import android.location.Location;
 import android.location.LocationListener;
 import android.location.LocationManager;
 import android.os.Bundle;
 import android.util.Log;
 public class audio extends Activity
 {
     /** Called when the activity is first created. */
     LocationManager locationManager;
     LocationListener llistener;
     String provider;
     public void onCreate(Bundle savedInstanceState)
     {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);
         Criteria criteria = new Criteria();
         criteria.setAccuracy(Criteria.ACCURACY_FINE);
         criteria.setAltitudeRequired(false);
         criteria.setBearingRequired(false);
         criteria.setCostAllowed(true);
         criteria.setPowerRequirement(Criteria.POWER_LOW);
         String serviceName = Context.LOCATION_SERVICE;
         locationManager = (LocationManager) getSystemService(serviceName);
         locationManager.setTestProviderEnabled("gps", true);
         provider = locationManager.getBestProvider(criteria, true);
         Log.d("provider", provider);
         llistener = new LocationListener() {
             @Override
             public void onLocationChanged(Location location)
             {
                 // TODO Auto-generated method stub
                 Log.i("onLocationChanged", "come in");
                 if (location != null)
                 {
                     Log.w("Location", "Current altitude = "
                             + location.getAltitude());
                     Log.w("Location", "Current latitude = "
                             + location.getLatitude());
                 }
                 locationManager.removeUpdates(this);
                 locationManager.setTestProviderEnabled(provider, false);
             }
             @Override
             public void onProviderDisabled(String provider)
             {
                 // TODO Auto-generated method stub
                 Log.i("onProviderDisabled", "come in");
             }
             @Override
             public void onProviderEnabled(String provider)
             {
                 // TODO Auto-generated method stub
                 Log.i("onProviderEnabled", "come in");
             }
             @Override
             public void onStatusChanged(String provider, int status,
                     Bundle extras)
             {
                 // TODO Auto-generated method stub
                 Log.i("onStatusChanged", "come in");
             }
         };
          locationManager.requestLocationUpdates(provider, 1000, (float) 1000.0, llistener);
     }
     protected void onDestroy()
     {
         locationManager.removeUpdates(llistener);
         locationManager.setTestProviderEnabled(provider, false);
         super.onDestroy();
     }

##More Android opens GPS navigation and obtains Please pay attention to the PHP Chinese website for related articles on the solution for returning null location information!


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
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.

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 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

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools