After doing a deep research, I found what I think is the easiest way to send GPS location (Latitude,Longitude) in a query string. Maybe there's no shorter code in the web than this. So we'll do this in 2 steps:
First add this permissions to the
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Now the code in your
MainActivity.java
inside the classpublic class MainActivity extends Activity { }
public class MainActivity extends Activity { public double latitude; public double longitude; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_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) { latitude = loc.getLatitude(); longitude = loc.getLongitude(); String Text = "My current Latitude = " + latitude + " Longitude = " + longitude; Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show(); SendQueryString(); // for send the Query String of latitude and logintude to the webapp. } @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) { } }/* End of Class MyLocationListener */ public void SendQueryString() { new Thread() { public void run() { String url = "http://mywebapp.com/coordinates/create?latitude=" + latitude +"&longitude=" + longitude; try { HttpClient Client = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); Client.execute(httpget); } catch(Exception ex) { String fail = "Fail!"; Toast.makeText( getApplicationContext(),fail,Toast.LENGTH_SHORT).show(); } } }.start(); } }
NOTE: As you can see I'm using new Thread() { public void run() {/*code here*/}}.start();
in the function SendQueryString()
, that's because we're trying to make a request to a server, so in Android you can't make a request to a server in the principal Thread, where the graphics and principal process are. In fact it'll return an error if you try to make a request in the principal Thread.