GPS 位置始终返回 null

Posted

技术标签:

【中文标题】GPS 位置始终返回 null【英文标题】:GPS Location returns always null 【发布时间】:2020-03-24 21:15:21 【问题描述】:

我试图在我的活动中访问gps 位置,但在调用getLastKnownLocationLocationManager 类时总是得到null。我还添加了以下权限。我的 GPS 已启用,但设备上没有互联网。请指导我做错了什么

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

并且还签入代码。下面是我的代码。

public class MainActivity extends  AppCompatActivity implements LocationListener 
    private TextView latituteField;
    private TextView longitudeField;
    private LocationManager locationManager;
    private String provider;

    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try 
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) 

                ActivityCompat.requestPermissions(this, new String[]Manifest.permission.ACCESS_FINE_LOCATION,
                        2);

            
         catch (Exception e) 
            e.printStackTrace();
        


        latituteField = (TextView) findViewById(R.id.TextView02);
        longitudeField = (TextView) findViewById(R.id.TextView04);

        // Get the location manager
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null)
            latituteField.setText(location.getLatitude()+"");
            longitudeField.setText(location.getLongitude()+"");
        else
            latituteField.setText("not found");
            longitudeField.setText("not found");
        

    



    @Override
    public void onLocationChanged(Location location) 
        int lat = (int) (location.getLatitude());
        int lng = (int) (location.getLongitude());
        latituteField.setText(String.valueOf(lat));
        longitudeField.setText(String.valueOf(lng));
    

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) 
        // TODO Auto-generated method stub

    

    @Override
    public void onProviderEnabled(String provider) 
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();

    

    @Override
    public void onProviderDisabled(String provider) 
        Toast.makeText(this, "Disabled provider " + provider,
                Toast.LENGTH_SHORT).show();
    

【问题讨论】:

快速检查方法是在同一部手机中打开谷歌地图并检查它是否显示当前位置 地图给了我正确的位置 行前" locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); " 。您需要检查您的设备上是否有gps/位置设置。如果没有打开意味着您需要将其设为开启。如果位置设置为关闭,则位置值可能为空。 位置设置已开启,我可以在我的活动开启时看到位置图标。 Map is giving me my correct location 通过使用 wifi。如果 gps 没有打开,它也会。 【参考方案1】:

在你的 build.gradle 中实现它,

implementation 'com.google.android.gms:play-services-location:17.0.0'

试试这个代码。它对我来说很好用..

package com.example.geolocation;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

public class MainActivity extends AppCompatActivity implements LocationListener 
    private TextView latituteField;
    private TextView longitudeField;
    private LocationManager locationManager;
    private String provider;
    private FusedLocationProviderClient fusedLocationClient;
    private String TAG=MainActivity.class.getSimpleName();
    LocationCallback mLocationCallback;

    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try 
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) 

                ActivityCompat.requestPermissions(this, new String[]Manifest.permission.ACCESS_FINE_LOCATION,
                        2);

            
         catch (Exception e) 
            e.printStackTrace();
        


        latituteField = (TextView) findViewById(R.id.TextView02);
        longitudeField = (TextView) findViewById(R.id.TextView04);

        // Get the location manager
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
            Log.d(TAG, "onCreate: not enabled gps");
        else 
            LocationRequest mLocationRequest = LocationRequest.create();
            mLocationRequest.setInterval(60000);
            mLocationRequest.setFastestInterval(5000);
            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            mLocationCallback = new LocationCallback() 
                @Override
                public void onLocationResult(LocationResult locationResult) 
                    if (locationResult == null) 
                        Log.d(TAG, "locationStatusCheck: onLocationResult null");
                        return;
                    
                    for (Location location : locationResult.getLocations()) 
                        if (location != null) 
                            //TODO: UI updates.
                            Log.d(TAG, "locationStatusCheck: onLocationResult not null");
                            double lat = (location.getLatitude());
                            double lng = (location.getLongitude());
                            latituteField.setText(String.valueOf(lat));
                            longitudeField.setText(String.valueOf(lng));
                            Log.d(TAG, "latitudeField: " + latituteField);
                            Log.d(TAG, "longitudeField: " + longitudeField);
                        
                    
                
            ;
            LocationServices.getFusedLocationProviderClient(getApplicationContext()).requestLocationUpdates(mLocationRequest, mLocationCallback, null);
        
    
    @Override
    public void onLocationChanged(Location location) 
        int lat = (int) (location.getLatitude());
        int lng = (int) (location.getLongitude());
        latituteField.setText(String.valueOf(lat));
        longitudeField.setText(String.valueOf(lng));
    

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) 

    

    @Override
    public void onProviderEnabled(String provider) 
        Toast.makeText(this, "Enabled new provider " + provider,
                Toast.LENGTH_SHORT).show();
    

    @Override
    public void onProviderDisabled(String provider) 
        Toast.makeText(this, "Disabled provider " + provider,
                Toast.LENGTH_SHORT).show();
    



【讨论】:

以上是关于GPS 位置始终返回 null的主要内容,如果未能解决你的问题,请参考以下文章

来自 LocationClient 的 getLastLocation() 始终返回 null [重复]

融合位置始终返回 null

使用PendingIntent获取位置始终返回Null

Android 网络提供商和 GPS 提供商返回 null

FusedLocationProvider 始终返回 null Location 对象

GetLastLocation 始终返回 null