-1

这是我在 android 中的代码并且显示错误。我不知道出了什么问题,但我很确定它必须做一些事情,LocationManager因为直到那条线它工作正常。

  public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Log.d("Exception", "Something gone wrong !! ");

/*after this line it shows error */

        LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        double longitude = location.getLongitude();
        double latitude = location.getLatitude();

我现在想要的只是显示经度和纬度的值,以便我可以确定代码到这里为止是好的。

4

2 回答 2

0

使用下面的代码片段

public void onCreate(Bundle savedInstanceState)
{
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

  /* Use the LocationManager class to obtain GPS locations */
  LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

  LocationListener mlocListener = new MyLocationListener();
  mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}

/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{

  @Override
  public void onLocationChanged(Location loc)
  {

    loc.getLatitude();
    loc.getLongitude();

    String Text = "My current location is: " +
    "Latitud = " + loc.getLatitude() +
    "Longitud = " + 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)
  {

  }
}

检查清单文件中的以下行

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
于 2012-07-30T12:06:31.817 回答
0

声明这个变量

 Location loc;

在 Oncreate() 方法中编写此代码

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

LocationListener mlocListener = new MyLocationListener();

mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);

然后写

loc.getLatitude();
loc.getLongitude();

现在您可以使用纬度和经度的值... :-)

于 2012-07-30T12:59:48.047 回答