Home >Java >javaTutorial >Android opens GPS navigation and obtains location information and returns null solution

Android opens GPS navigation and obtains location information and returns null solution

高洛峰
高洛峰Original
2017-01-07 14:47:211988browse

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