如何在Android中使用GPS获取位置?

时间:2017-08-30 06:44:03

标签: java android gps

我想检测我的位置,我正在使用 ACCESS_FINE_LOCATION 权限,但是当我运行应用时,它会崩溃并在屏幕上出现错误消息:

  

" AppName的"已停止工作

以下是我的代码,我用来实现上面说的:

public class MainActivity extends AppCompatActivity {
    LocationManager locationManager;
    Location location;

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

       locationManager = (LocationManager) 
                       getSystemService(Context.LOCATION_SERVICE);
       if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
           return;
       }
       location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
       Log.v("My Coordinates are: ", location.getLatitude() + " " + location.getLongitude());
    }
}

我在这里做错了什么?

请帮助。

1 个答案:

答案 0 :(得分:0)

将您的权限放入清单中,这样您就不需要在其他活动中再次使用该代码

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

实现位置管理员:

LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);

如果启用了gps,则获取坐标:

LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 5000, 10, locationListener);

这是完整实施的样本:

private class MyLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location loc) {
        editLocation.setText("");
        pb.setVisibility(View.INVISIBLE);
        Toast.makeText(
                getBaseContext(),
                "Location changed: Lat: " + loc.getLatitude() + " Lng: "
                    + loc.getLongitude(), Toast.LENGTH_SHORT).show();
        String longitude = "Longitude: " + loc.getLongitude();
        Log.v(TAG, longitude);
        String latitude = "Latitude: " + loc.getLatitude();
        Log.v(TAG, latitude);

        /*------- To get city name from coordinates -------- */
        String cityName = null;
        Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
        List<Address> addresses;
        try {
            addresses = gcd.getFromLocation(loc.getLatitude(),
                    loc.getLongitude(), 1);
            if (addresses.size() > 0) {
                System.out.println(addresses.get(0).getLocality());
                cityName = addresses.get(0).getLocality();
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        String s = longitude + "\n" + latitude + "\n\nMy Current City is: "
            + cityName;
        editLocation.setText(s);
    }

    @Override
    public void onProviderDisabled(String provider) {}

    @Override
    public void onProviderEnabled(String provider) {}

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