LocationManager生成错误代码

问题描述:

这是我在android中的代码并显示错误。我不知道什么是错,但我很高兴它必须做一些与LocationManager,因为直到该行它的工作正常。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(); 

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

+3

什么错误logcat ..和你使用设备或模拟器? – Youddh 2012-07-30 11:43:37

Declate这个变量

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

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

清单文件,使用下面的代码片段

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"/> 
+0

这会在每次我的GPS坐标改变时读取坐标。但我想要的应用程序初始化时的坐标值。可以做到吗? – Leonidus 2012-07-30 12:22:09

+0

是在应用程序启动时将坐标值存储到变量中。 – Yash 2012-07-30 12:28:07

+0

请你详细说明一下吗? – Leonidus 2012-07-30 12:31:59