LocationManager在代码中生成错误

时间:2012-07-30 11:41:56

标签: android

这是我在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();

我现在想要的只是显示经度和纬度的值,这样我才能确定代码是好的。

2 个答案:

答案 0 :(得分: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"/>

答案 1 :(得分: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();

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