2013-10-02 41 views
1

我是新來的andriod任何人都可以請教我如何創建一個應用程序wic發現gps位置按下按鈕。我找到了一些代碼來找到位置,但不知道如何使用它。如何開發應用程序來查找GPS位置

public class GPS_Location extends Activity implements LocationListener { 

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

     LocationManager locationManager = (LocationManager)  getSystemService(Context.LOCATION_SERVICE); 
     locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     // Inflate the menu; this adds items to the action bar if it is present. 
     getMenuInflater().inflate(R.menu.gps__location, menu); 
     return true; 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     double latitude =location.getLatitude(); 
     double longitude =location.getLongitude(); 

     Log.i("Geo_Location", "Latitude: " + latitude + ", Longitude: " + longitude); 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
     // TODO Auto-generated method stub 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
     // TODO Auto-generated method stub 
    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 
     // TODO Auto-generated method stub 
    } 
} 
+0

我寫了一篇博客,說明它在一個小細節,但你不得不做的*事*:HTTP ://scotthel.me/androidgps –

回答

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

您需要在您的清單,這些permisions:

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

這隻有在您的GPS已啓用時纔有效。由'getLastKnownLocation'檢索的'Location'可能不是當前位置。 – Emmanuel

相關問題