我正在尝试通过GPS获取当前位置。但是我的应用程序意外关闭。我不知道原因。我在AndroidManifest.xml中增加了权限:

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


我正在尝试的代码如下:

公共类MainActivity扩展了Activity {

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

public void getLoc()
{
    LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    LocationListener listener = new MyLocationListener();
    manager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5000, 10, listener);
}

public class MyLocationListener implements LocationListener    {
@Override

public void onLocationChanged(Location loc)
{
    loc.getLatitude();
    loc.getLongitude();
    String Text = "My current location is: " + "Latitude = " + loc.getLatitude() + "Longitude = " + loc.getLongitude();
    Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
}

@Override

public void onProviderDisabled(String provider)
{
    Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}

@Override

public void onProviderEnabled(String provider)
{
    Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}

@Override

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


}

最佳答案

尝试这个。
首先,使此代码简单。

在onCreate中添加此行,因为我看不到onCreate中调用的任何getloc方法

LocationManager manager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    LocationListener listener = new MyLocationListener();
    manager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5000, 10, listener);


为了进行测试,请将这些值更改为0

manager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, listener);


并使用此方法更改onLocationChange。

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));
  }


或尝试这个link

10-02 09:28