


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

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

Start Spring using IntelliJIDEAUltimate version...

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...
