import java.io.IOException; import java.util.List; import java.util.Locale; import android.app.Activity; import android.content.Context; import android.location.Address; import android.location.Geocoder; import android.location.GpsSatellite; import android.location.GpsStatus.Listener; import android.location.Location; import android.location.GpsStatus; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.os.SystemClock; import android.util.Log; import android.view.Menu; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity { String TAG = "GPS Location"; private TextView myLongitude; private TextView myAddress ; private TextView myLatitude; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myLatitude = (TextView)findViewById(R.id.mylatitude); myLongitude = (TextView)findViewById(R.id.mylongitude); myAddress = (TextView)findViewById(R.id.myaddress); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); LocationListener locationListener = new MyLocationListener(); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener); } class MyLocationListener implements LocationListener{ @Override public void onLocationChanged(Location loc) { System.out.println("location change"); Toast.makeText( getBaseContext(), "Location changed: Lat: " + loc.getLatitude() + " Lng: " + loc.getLongitude(), Toast.LENGTH_LONG).show(); String longitude = "Longitude: " + loc.getLongitude(); Log.v(TAG, longitude); myLongitude.setText(longitude); String latitude = "Latitude: " + loc.getLatitude(); Log.v(TAG, latitude); myLatitude.setText(latitude); String cityName = null; Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
and XML:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Location" android:background="#505050" /> <TextView android:id="@+id/mylatitude" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:id="@+id/mylongitude" android:layout_width="fill_parent" android:layout_height="wrap_content" /> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Address" android:background="#505050" /> <TextView android:id="@+id/myaddress" android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout>
use this permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
make sure the hardware gps device.
source share