【问题标题】:My Location App is not accessing the getLastKnownLocation我的位置应用程序未访问 getLastKnownLocation
【发布时间】:2016-06-17 12:51:27
【问题描述】:

我正在尝试检索设备的位置,但由于某种原因没有接收到该位置。有人可以检查我的代码并让我知道代码中的错误是什么。谢谢。

MainActivity

 public class MainActivity extends AppCompatActivity implements LocationListener {
    LocationManager locManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //get a reference to the location services to initialize the location manager object
        locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


        // Creating an empty criteria object
        Criteria criteria = new Criteria();

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }

        // Get name of the provider in this case which would be gps
       // String provider = locManager.getBestProvider(criteria, false);

       // if (provider != null && !provider.equals("")) {
            // Get the location
          //  Location location = locManager.getLastKnownLocation(provider);


Location location = getLastKnownLocation();

        private Location getLastKnownLocation() {
            LocationManager mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
            List<String> providers = mLocationManager.getProviders(true);
            Location bestLocation = null;
            for (String provider : providers) {
                Location l = mLocationManager.getLastKnownLocation(provider);
                if (l == null) {
                    continue;
                }
                if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
                    // Found best last known location: %s", l);
                    bestLocation = l;
                }
            }
            return bestLocation;
        }
            //set frequency of location update parameters
            locManager.requestLocationUpdates(provider, 120000, 10, this);

            if (location != null)
                onLocationChanged(location);
            else {
                TextView tvLongitude = (TextView) findViewById(R.id.curr_longitude);
                tvLongitude.setText("Location can't be retrieved");
                Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
            }

     /*   } else {
            //create a toast indicating error.
            Toast.makeText(getBaseContext(), "OOPS something went wrong", Toast.LENGTH_SHORT).show();

        }*/
}


    public void onLocationChanged(Location location) {
        // text view for company caption
        TextView jackFruit = (TextView) findViewById(R.id.jack_fruit);
        // Get TextView curr_longitude
        TextView tvLongitude = (TextView) findViewById(R.id.curr_longitude);

        // Getting TextView curr_latitude
        TextView tvLatitude = (TextView) findViewById(R.id.curr_latitude);

        // setting company caption
        jackFruit.setText("Jackfruit Systems: My current location");

        // Setting Current Longitude in the TextView
        tvLongitude.setText("Longitude:" + location.getLongitude());

        // Setting Current Latitude in the TextView
        tvLatitude.setText("Latitude:" + location.getLatitude());
    }

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.jackfruit.driverlocationinfo">

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

【问题讨论】:

  • 可能需要添加权限&lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/&gt;
  • 嗨,我试过了,还是不行。由于某种原因,它没有检测到提供者。
  • 你的目标版本是什么?如果是 23,那么你需要在运行时请求权限。
  • 嗨 Artem,我只需调用 requestLocationUpdate 并删除 getLastKnownLocation 就可以了。我还检查了一个 youtube 视频以实现 sdk 版本 23 的权限。感谢您的帮助,非常感谢。
  • 太棒了!我的祝贺!您可以发布您的代码作为答案,以便在这种情况下帮助其他人。

标签: java android android-studio geolocation android-gps


【解决方案1】:

我为 sdk 版本 23 尝试了另一种方法。

MainActivity

 @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
// calling location service via location manager
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        //calling location listener to get location coordinates on change of location
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                altitude = location.getAltitude();//calling altitude
                longitude = location.getLongitude();//calling longitude
                latitude = location.getLatitude();//calling latitude

                longitudeValue = Double.toString(longitude);//converting double longitude to string
                latitudeValue = Double.toString(latitude);//converting double latitude to string
                altitudeValue = Double.toString(altitude);//converting double altitude to string
            }

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

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {
                //calling settings options in device when location is disabled
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
            }
        };
        // adding permissions for location service for api level 23
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            requestPermissions(new String[]{
                    Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
                    Manifest.permission.INTERNET
            }, 10);
            return;
        } else {
            //after above check start the method:
            locationConfiguration();
        }
}

    //another permission check if the first permissions miss any permission lib. packages
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 10:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                    locationConfiguration();
                return;
        }
    }


    //method to call location provider
    private void locationConfiguration() {
        provider = locationManager.getProvider(LocationManager.GPS_PROVIDER);
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, locationListener);
        provider.supportsAltitude();

    }

【讨论】:

    【解决方案2】:

    如果您为Android 6.0+编译应用程序,您需要在运行时请求权限。

    有代码,Android Studio 建议Location location = locManager.getLastKnownLocation(provider);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
    

    这是官方文档的the link

    编辑 我试图在我的手机上运行这段代码。这没有用:) that question 的代码帮助了我:

    public class MainActivity extends AppCompatActivity implements LocationListener {
     LocationManager locManager;
    
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
      setSupportActionBar(toolbar);
      //get a reference to the location services to initialize the location manager object
      locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    
    
      // Creating an empty criteria object
      Criteria criteria = new Criteria();
    
      if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
       return;
      }
    
      // Get name of the provider in this case which would be gps
      // String provider = locManager.getBestProvider(criteria, false);
    
      // if (provider != null && !provider.equals("")) {
      // Get the location
      //  Location location = locManager.getLastKnownLocation(provider);
    
    
      Location location = getLastKnownLocation();
    
    
      //set frequency of location update parameters
      locManager.requestLocationUpdates(provider, 120000, 10, this);
    
      if (location != null)
       onLocationChanged(location);
      else {
       TextView tvLongitude = (TextView) findViewById(R.id.curr_longitude);
       tvLongitude.setText("Location can't be retrieved");
       Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
      }
    
      /*   } else {
                    //create a toast indicating error.
                    Toast.makeText(getBaseContext(), "OOPS something went wrong", Toast.LENGTH_SHORT).show();
    
                }*/
     }
    
     private Location getLastKnownLocation() {
      if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
       return;
      }
      LocationManager mLocationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
      List < String > providers = mLocationManager.getProviders(true);
      Location bestLocation = null;
      for (String provider: providers) {
       Location l = mLocationManager.getLastKnownLocation(provider);
       if (l == null) {
        continue;
       }
       if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
        // Found best last known location: %s", l);
        bestLocation = l;
       }
      }
      return bestLocation;
     }
    
     public void onLocationChanged(Location location) {
      // text view for company caption
      TextView jackFruit = (TextView) findViewById(R.id.jack_fruit);
      // Get TextView curr_longitude
      TextView tvLongitude = (TextView) findViewById(R.id.curr_longitude);
    
      // Getting TextView curr_latitude
      TextView tvLatitude = (TextView) findViewById(R.id.curr_latitude);
    
      // setting company caption
      jackFruit.setText("Jackfruit Systems: My current location");
    
      // Setting Current Longitude in the TextView
      tvLongitude.setText("Longitude:" + location.getLongitude());
    
      // Setting Current Latitude in the TextView
      tvLatitude.setText("Latitude:" + location.getLatitude());
     }
    
     @Override
     public void onStatusChanged(String provider, int status, Bundle extras) {
    
     }
    
     @Override
     public void onProviderEnabled(String provider) {
    
     }
    
     @Override
     public void onProviderDisabled(String provider) {
    
     }
    }
    

    对我来说,首选提供商是“gps”,但它返回null Location。

    附:抱歉格式化。您可以在 Android Studio 中按 Ctrl+Alt+L 来正确格式化。

    【讨论】:

    • 好的,这是 android studio 建议的,我之前应用了它。有了这个权限,提供者根本不会被检测到。我调试时它甚至不返回 null 。有什么想法吗?
    • 你能更新你的代码吗?当您检查权限时 - 在locManager.getBestProvider(criteria, false); 之前还是之后?
    • 我已经更新了我的代码。检查权限在 String provider = locManager.getBestProvider(criteria, false); 之前
    • 你能告诉我,如何在我的代码中实现它吗?这让我很困惑。
    • 您需要复制粘贴该新功能并按照答案中的说明进行操作
    猜你喜欢
    • 2018-12-24
    • 2011-06-08
    • 1970-01-01
    • 2018-03-02
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 2013-05-30
    • 1970-01-01
    相关资源
    最近更新 更多