Hi I'm currently learning about the GPS for development in Android. Now I've read about the basics through vogellas blog here. Now I already get the latitude and longitude and displayed it on my device but I don't know why it doesn't update my location even though I already set a runnable thread to fetch location every 3 seconds. Same reason why I can't check if I got the correct formula to get the total distance I've travelled.
This is my first time working with this so maybe someone can give me a tip or idea on how to.
I created a repository in github maybe someone can help me with this. See file here :)
EDIT:
Okay the main problem is that the onChangeLocation() seems doesn't work on my end. What I tried is to create a runnable to display the location every 3 seconds but it doesn't return the result I expected.
Did I missed out on something here?
Here's my code so far for easier viewing:
Main.java
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.provider.Settings;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
/*created by Kahel 08/16/2013
* to read more about the location manager go here: http://www.vogella.com/articles/AndroidLocationAPI/article.html
*
* */
public class Main extends Activity implements LocationListener {
private TextView latitude, longitude, distance;
private Button getLocation;
private LocationManager locationManager;
private String provider;
double distance_travelled;
double latitude_prev;
double longitude_prev;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latitude = (TextView)findViewById(R.id.txt_latitude);
longitude = (TextView)findViewById(R.id.txt_longitude);
distance = (TextView) findViewById(R.id.txt_distance);
getLocation = (Button)findViewById(R.id.btn_getLocation);
checkGps();
getCurrentLocation();
getLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
locatorRunner();
}
});
}
private void locatorRunner(){
Thread thread = new Thread()
{
#Override
public void run() {
try {
while(true) {
sleep(3000);
runOnUiThread(new Runnable() {
#Override
public void run() {
/*needs UI Thread*/
getCurrentLocation();
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
thread.start();
}
private void getCurrentLocation(){
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
Toast.makeText(Main.this,String.valueOf(location),Toast.LENGTH_SHORT).show();
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f, (LocationListener) location);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latitude.setText("Location not available");
longitude.setText("Location not available");
distance.setText("0");
}
}
private void checkGps(){
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
Toast.makeText(Main.this,String.valueOf(enabled),Toast.LENGTH_SHORT).show();
// Check if enabled and if not send user to the GSP settings
// Better solution would be to display a dialog and suggesting to
// go to the settings
if (!enabled) {
showGpsSettingDialog();
}
}
private void showGpsSettingDialog(){
/*Create a dialog to tell user to enable his GPS settings to pinpoint his or her location*/
AlertDialog.Builder alertDialog = new AlertDialog.Builder(Main.this);
alertDialog.setTitle("Settings para sa lokasyon"); /*should be on a string values*/
alertDialog
.setMessage("Kasalukuyang hindi aktibo ang iyong GPS para makuha ang iyong lokasyon. Nais mo bang i-set ito ngayon?")
.setCancelable(false)
.setPositiveButton("Oo", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton("Hindi", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog gpsSettingsDialog = alertDialog.create();
gpsSettingsDialog.show();
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(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.main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
getLocation(location);
}
private void getLocation(Location location){
int R = 6371;
double lat = location.getLatitude();
double lon = location.getLongitude();
latitude_prev = lat;
longitude_prev = lon;
Double dlat = latitude_prev - lat;
Double dlon = longitude_prev - lon;
double a = Math.sin(dlat / 2) * Math.sin(dlat / 2) + Math.cos(latitude_prev) *
Math.cos(lat) * Math.sin(dlon / 2) * Math.sin(dlon / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
distance_travelled = R * c;
latitude.setText(String.valueOf(lat));
longitude.setText(String.valueOf(lon));
distance.setText(String.valueOf(distance_travelled));
}
/*private double toRad(double d) {
return d * Math.PI / 180;
}*/
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(this, "Enabled new provider " + provider,Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(this, "Disabled provider " + provider,Toast.LENGTH_SHORT).show();
}
}
main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40dip"
android:orientation="horizontal" >
<TextView
android:id="#+id/TextView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:text="Latitude: "
android:textSize="20dip" >
</TextView>
<TextView
android:id="#+id/txt_latitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="unknown"
android:textSize="20dip" >
</TextView>
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dip"
android:layout_marginRight="5dip"
android:text="Longitute: "
android:textSize="20dip" >
</TextView>
<TextView
android:id="#+id/txt_longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="unknown"
android:textSize="20dip" >
</TextView>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Distance Travelled:"
android:id="#+id/textView"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="unknown"
android:id="#+id/txt_distance"/>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Location"
android:id="#+id/btn_getLocation"
android:layout_gravity="center"/>
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.geolocation"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION " />
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="10" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.geolocation.Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Note:
I added the button Start Tracking because I'm not sure if the onLocationChanged is working or not. hahaha!
Basic approach for distance:
public class test extends Activity implements LocationListener{
private LocationManager lm;
private Location last;
private long distance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
}
#Override
protected void onResume() {
super.onResume();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,1,this);
}
#Override
protected void onPause() {
super.onPause();
lm.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
if(last != null){
distance += location.distanceTo(last);
}
last = new Location(location);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
You have to implement LocationListener to get current GPS location something like this :
Set user permission firlst
Now get GPS location like this :
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
/*----------Listener class to get coordinates ------------- */
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
//Get your location here
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
You can call getCurrentLocation() every 3 second but this will not trigger getLocation(location);.
getLocation(location); will be called only when Location gets updated
#Override
public void onLocationChanged(Location location) {
getLocation(location);
}
Related
If I click "Find My Location" button, then my location information should have shown on the TextView, but doesn't work.
It's simple code but I have no idea where did this go wrong. Seems that there's no mistake within the code.. could be the problem of my phone?
MainActivity.java
package org.androidtown.mylocation;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
}
public void onButton1Clicked(View v){
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
long minTime = 10000;
float minDistance = 0;
MyLocationListener listener = new MyLocationListener();
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
minTime, minDistance, listener);
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
minTime, minDistance, listener);
Location lastLocation = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastLocation != null){
Double latitude = lastLocation.getLatitude();
Double longitude = lastLocation.getLongitude();
textView.setText("My Latest Location: " + latitude + ", " + longitude);
textView.invalidate();
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
textView.setText("My Location: " + latitude + ", " + longitude);
textView.invalidate();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.androidtown.mylocation" >
<!-- GPS -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!-- NETWORK -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Find My Location"
android:id="#+id/button"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:onClick="onButton1Clicked" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My Location"
android:id="#+id/textView"
android:layout_below="#+id/button"
android:layout_centerHorizontal="true"
android:layout_marginTop="83dp" />
</RelativeLayout>
So i put together a few snippets that i found here and there; aiming to make a more complex app, however, at one point i was able to obtain the the longitude and latitude number, but once I've tried supply those number to the reverse GeoCoding mechanism, i have not been able to get the Long and Lat numbers and the app crashes after i click the button (which does the reverse geocoding)
package com.example.com.example;
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.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
Button myLocation;
TextView myAddress;
TextView textLat;
TextView textLong;
double latHolder = 0.0;
double longHolder = 0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myLocation= (Button) findViewById(R.id.location);
myAddress = (TextView)findViewById(R.id.address);
textLat = (TextView)findViewById(R.id.textLat); ///COORDINATION VARIABLES1
textLong = (TextView)findViewById(R.id.textLong);///2
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); //gets it from the Operating system
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll); //LOCATION UPDATED LINKED
if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
textLat.setText("GPS ONLINE (PLEASE WAIT)");
textLong.setText("GPS ONLINE (PLEASE WAIT)");
}
else
{
textLat.setText("GPS OFFLINE");
textLong.setText("GPS OFFLINE");
}
myLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getMyLocationAddress();
}
});
}
///////////COORDIATION ACQUIRING DOWN HERE
private class mylocationlistener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if(location != null)
{
double pLat = location.getLatitude();
double pLong = location.getLongitude();
textLat.setText(Double.toString(pLat));
textLong.setText(Double.toString(pLong));
latHolder = pLat;
longHolder = pLong;
}
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
}
public void getMyLocationAddress() {
Geocoder geocoder= new Geocoder(this, Locale.ENGLISH);
try {
//Place your latitude and longitude
List<Address> addresses = geocoder.getFromLocation(latHolder,longHolder, 1);
if(addresses != null) {
Address fetchedAddress = addresses.get(0);
StringBuilder strAddress = new StringBuilder();
for(int i=0; i<fetchedAddress.getMaxAddressLineIndex(); i++) {
strAddress.append(fetchedAddress.getAddressLine(i)).append("\n");
}
myAddress.setText("I am at: " +strAddress.toString());
}
else
myAddress.setText("No location found..!");
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Could not get address..!", Toast.LENGTH_LONG).show();
}
}
}
Here is my Manafist with all permissions which should be enough
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.com.example"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<permission android:name="com.example.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
and last but not lease my xml layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LATITUDE" />
<Button
android:id="#+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/address"
android:layout_below="#+id/address"
android:layout_marginTop="79dp"
android:text="get_location" />
<TextView
android:id="#+id/address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/title"
android:layout_below="#+id/title"
android:layout_marginTop="135dp" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/title"
android:layout_below="#+id/title"
android:layout_marginTop="44dp"
android:text="LONGITUD" />
<TextView
android:id="#+id/textLong"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="26dp" />
<TextView
android:id="#+id/textLat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/title"
android:layout_below="#+id/title" />
</RelativeLayout>
DO PLEASE NOTE! i have added two global variables called LongHolder and LatHolder to pass the values of the GPS straight to the reverse geocoding. I believe they failed their purpose but if you need to test random selected Coordinates yourself, remember to remove them. THANK YOU
I try to implement a gps application, (I take the code from a guide) but doesn't work!
I think the problem is the provider enabled, so the app can't calculate the latitude and longitude.
Please help me, thank you.
package it.wstech.gps;
import java.util.Date;
import android.app.Activity;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.widget.TextView;
public class GPSMainActivity extends Activity {
private String providerId= LocationManager.GPS_PROVIDER;
private LocationListener myLocationListener= new LocationListener(){
//methods of Location Listener interface
#Override
public void onStatusChanged (String provider, int status, Bundle extras){
if (status==LocationProvider.AVAILABLE){
setTextViewValue(R.id.available,"TRUE");
}
else {
setTextViewValue(R.id.available,"FALSE");
}
}
#Override
public void onProviderEnabled (String provider){
setTextViewValue(R.id.enabled,"TRUE");
}
#Override
public void onProviderDisabled (String provider){
setTextViewValue(R.id.enabled,"FALSE");
}
#Override
public void onLocationChanged (Location location){
updateLocationData(location);
}
};
//activity methods
#Override
public void onCreate (Bundle savedIstanceState){
super.onCreate(savedIstanceState);
setContentView(R.layout.activity_gpsmain);
}
#Override
protected void onResume(){
super.onResume();
setTextViewValue(R.id.provider,providerId);
LocationManager locationManager = (LocationManager) getSystemService (LOCATION_SERVICE);
LocationProvider provider= locationManager.getProvider(providerId);
if (provider== null) {
setTextViewValue (R.id.available,"FALSE");
} else {
setTextViewValue (R.id.available,"TRUE");
boolean gpsEnabled=locationManager.isProviderEnabled(providerId);
if (gpsEnabled){
setTextViewValue (R.id.enabled,"TRUE");
}
else {
setTextViewValue (R.id.enabled,"FALSE");
}
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location !=null){
updateLocationData(location);
}
locationManager.requestLocationUpdates(providerId, 5, 1,myLocationListener);
}
}
#Override
protected void onPause(){
super.onPause();
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.removeUpdates(myLocationListener);
}
private void setTextViewValue (int textViewId, String value){
TextView testView=(TextView) findViewById(textViewId);
if (testView!=null){
testView.setText(value);
}
}
private void updateLocationData(Location location){
Date timestamp= new Date (location.getTime());
setTextViewValue (R.id.timestamp, timestamp.toString());
double latitude=location.getLatitude();
setTextViewValue (R.id.latitude, String.valueOf(latitude));
double longitude = location.getLongitude();
setTextViewValue (R.id.longitude, String.valueOf(longitude));
if (location.hasAltitude()){
double altitude = location.getAltitude();
setTextViewValue (R.id.altitude, String.valueOf(altitude));
}
if (location.hasSpeed()){
float speed=location.getSpeed();
setTextViewValue(R.id.speed, String.valueOf(speed));
}
}
}
My activity_gpsmain.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TableRow
android:padding="5px">
<TextView
android:text="Provider"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/provider"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:padding="5px">
<TextView
android:text="Disponibile"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/available"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:padding="5px">
<TextView
android:text="Abilitato"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="#+id/enabled"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:padding="5px">
<TextView
android:text="Timestamp"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/timestamp"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:padding="5px">
<TextView
android:text="Latitudine"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/latitude"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:padding="5px">
<TextView
android:text="Longitudine"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="#+id/longitude"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:padding="5px">
<TextView
android:text="Altitudine"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="#+id/altitude"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:padding="5px">
<TextView
android:text="Velocità"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="#+id/speed"
android:padding="5px"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>
</ScrollView>
</LinearLayout>
my AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="it.wstech.gps"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name ="android.permission.ACCESS_FINE_LOCATION"/>
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".GPSMainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Result:
Provider gps
Disponibile TRUE
Abilitato false
Timestamp
Latitudine
Longitudine false
Altitudine false
Velocità false
Try this code and get latitude and longitude
Create a class GPSTracker.java
package com.example.gpstracker;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener
{
private final Context _context;
boolean isGPSEnabled=false;
boolean isNetworkEnabled=false;
boolean canGetLocation=false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=5; //5 meters
private static final long MIN_TIME_BW_UPDATES=1000*60*1; // 1 minute
protected LocationManager locationManager;
public GPSTracker(Context contet)
{
this._context=contet;
getLocation();
}
public Location getLocation()
{
try
{
locationManager =(LocationManager)_context.getSystemService(LOCATION_SERVICE);
//getting GPS Status
isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled)
{
}
else
{
this.canGetLocation=true;
//first get location from network provider
if(isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.i("Network","Network");
if(locationManager !=null)
{
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location !=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
// if GPS Enabled get lat/log
if(isGPSEnabled)
{
if(location == null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.i("GPS","GPS Enabled");
if(locationManager !=null)
{
location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location !=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
return location;
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude()
{
if(location !=null)
{
latitude=location.getLatitude();
}
return latitude;
}
public double getLongitude()
{
if(location !=null)
{
longitude=location.getLongitude();
}
return longitude;
}
public boolean canGetLocation()
{
return this.canGetLocation;
}
public void showSettingAlert()
{
AlertDialog.Builder alert=new AlertDialog.Builder(_context);
alert.setTitle("GPS is Setting");
alert.setMessage("GPS is not enabled. Do you want to go to settings..?");
alert.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
_context.startActivity(i);
}
});
alert.setNegativeButton("No",new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.show();
}
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Create your activity class file MainActivity.java
package com.example.gpstracker;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
Button btnClick;
GPSTracker tracker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnClick=(Button)findViewById(R.id.btnClick);
btnClick.setOnClickListener(this);
}
#Override
public void onClick(View v) {
tracker=new GPSTracker(getApplicationContext());
if(tracker.canGetLocation())
{
double latitude=tracker.getLatitude();
double longitude=tracker.getLongitude();
Toast.makeText(MainActivity.this,"your Location is \n Latitude : " + latitude +
"\n Longitude : "+longitude,Toast.LENGTH_LONG).show();
}
else
{
tracker.showSettingAlert();
}
}
}
Add below lines in manifest.xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
I'm very new to android. I'm developing an app which shows the current location using Google Map.
I've generated key for this application. But It doesn't show the map instead, it shows Grid View.
The following is the code..!
//MActivity
package velu.ndot.hosp;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class HospitalActivity extends MapActivity {
private LocationManager myLocationManager;
private LocationListener myLocationListener;
private TextView myLongitude, myLatitude;
private MapView myMapView;
private SeekBar myZoomBar;
private MapController myMapController;
private void CenterLocation(GeoPoint centerGeoPoint)
{
myMapController.animateTo(centerGeoPoint);
myLongitude.setText("Longitude: "+
String.valueOf((float)centerGeoPoint.getLongitudeE6()/1000000)
);
myLatitude.setText("Latitude: "+
String.valueOf((float)centerGeoPoint.getLatitudeE6()/1000000)
);
};
private void SetZoomLevel()
{
int myZoomLevel = myZoomBar.getProgress()+1;
myMapController.setZoom(myZoomLevel);
Toast.makeText(this,
"Zoom Level : " + String.valueOf(myZoomLevel),
Toast.LENGTH_LONG).show();
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newtab);
myMapView = (MapView)findViewById(R.id.mapview);
myLongitude = (TextView)findViewById(R.id.longitude);
myLatitude = (TextView)findViewById(R.id.latitude);
myZoomBar = (SeekBar)findViewById(R.id.zoombar);
myMapView.setSatellite(true); //Set satellite view
myMapController = myMapView.getController();
SetZoomLevel();
myLocationManager = (LocationManager)getSystemService(
Context.LOCATION_SERVICE);
myLocationListener = new MyLocationListener();
myLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
myLocationListener);
//Get the current location in start-up
//check LastKnownLocation, if not valid, skip it.
Location initLocation=
myLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(initLocation != null)
{
GeoPoint initGeoPoint = new GeoPoint(
(int)(initLocation.getLatitude()*1000000),
(int)(initLocation.getLongitude()*1000000));
CenterLocation(initGeoPoint);
}
myZoomBar.setOnSeekBarChangeListener(myZoomBarOnSeekBarChangeListener);
}
private SeekBar.OnSeekBarChangeListener myZoomBarOnSeekBarChangeListener =
new SeekBar.OnSeekBarChangeListener(){
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
SetZoomLevel();
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
};
private class MyLocationListener implements LocationListener{
public void onLocationChanged(Location argLocation) {
// TODO Auto-generated method stub
GeoPoint myGeoPoint = new GeoPoint(
(int)(argLocation.getLatitude()*1000000),
(int)(argLocation.getLongitude()*1000000));
CenterLocation(myGeoPoint);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
};
//Manifest file
This is my manifest.xml File and I have got permission with the internet
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="velu.ndot.hosp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:theme="#android:style/Theme.Light"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".HospitalActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<uses-library android:required="true" android:name="com.google.android.maps"> </uses-library>
</application>
</manifest>
//Layout
My layout design..!
<?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"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/longitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Longitude:"
/>
<TextView
android:id="#+id/latitude"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Latitude:"
/>
<SeekBar
android:id="#+id/zoombar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:max="20"
android:progress="0"/>
</LinearLayout>
<com.google.android.maps.MapView
android:id="#+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="false"
android:apiKey="key**********************"
/>
</LinearLayout>
This looking all right in your code. Please try to take another map key and then check may be this will solve your problem .
As your code is similar to:
http://www.mubasheralam.com/tutorials/android/how-use-google-maps-android-application
Ok i have tried Nicholas's solution but still getting force close if i press the back button as the app searches for gps fix.so i m uploading all the codes and files(except icon.png and pen.png in drawables) for the project...so that it's possible just to copy paste the code from here to see whats going on. my main.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"
android:background="#drawable/icon"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<Button android:text="Start"
android:id="#+id/Button01"
android:layout_width="120px"
android:layout_height="70px"
android:layout_gravity = "center_horizontal"
android:textSize="20px"
android:layout_marginTop="150px"
android:clickable="true"
></Button>
</LinearLayout>
next my main activity(GpsLocEx.java)
package com.example.gpslocex;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class GpsLocEx extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button start = (Button) findViewById(R.id.Button01);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent map = new Intent(view.getContext(), com.example.gpslocex.ShowMap.class);
startActivityForResult(map, 0);
}
});
}
}
next my gps.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/mainlayout"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<com.google.android.maps.MapView
android:id="#+id/mapview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:apiKey="06ZLf-HkdkRMb513KS2ZRljmMQL0bntlyMJ-rOQ"
/>
</RelativeLayout>
next ShowMap.java
package com.example.gpslocex;
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
public class ShowMap extends MapActivity {
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private GeoUpdateHandler geoUpdateHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gps);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(14); // Zoom 1 is world view
geoUpdateHandler = new GeoUpdateHandler();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
createGpsDisabledAlert();
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0,geoUpdateHandler);
}
}
private void createGpsDisabledAlert() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder
.setMessage(
"Your GPS is disabled! Would you like to enable it?")
.setCancelable(false).setPositiveButton("Enable GPS",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
showGpsOptions();
}
});
builder.setNegativeButton("Do nothing",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void showGpsOptions() {
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
mapController.animateTo(point); // mapController.setCenter(point);
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
class MapOverlay extends Overlay
{
private GeoPoint pointToDraw;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pen);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 128, null);
return true;
}
}
#Override
public void onPause() {
locationManager.removeUpdates(geoUpdateHandler);
}
}
next strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Version-1.0</string>
<string name="app_name">GpsLocEx</string>
</resources>
Finally AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.gpslocex"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="#drawable/icon" android:label="#string/app_name">
<uses-library android:name="com.google.android.maps" />
<activity android:name=".GpsLocEx"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ShowMap"></activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="ACCESS_COARSE_LOCATION" />
</manifest>
You can use the Android lifecycle methods to turn off the GPS when the Activity is no longer on top.
Use onPause(), onStop(), or onDestroy() to remove updates from your locationManager. Something like this:
#Override
public void onPause() {
locationManager.removeUpdates(myLocationListener);
}
EDIT:
You have a ClassCastException in your onPause() method. You cannot cast this (your Activity) to a LocationListener (at least not without making your Activity implement LocationListener).
In your code, you create a new GeoUpdateHandler(). First, you should create an instanceVariable that is your GeoUpdateHandler. Underneath your instance variable for LocationManager, create one like this:
private GeoUpdateHandler geoUpdateHandler;
You should keep a handle to this in the onCreate() method:
#Override
public void onCreate(Bundle savedInstanceState) {
//...some code here...
geoUpdateHandler = new GeoUpdateHandler();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0,geoUpdateHandler);
//...maybe some more code here...
}
And then in the onPause, pass the geoUpdateHandler to the removeUpdates function:
#Override
public void onPause() {
locationManager.removeUpdates(geoUpdateHandler);
}
EDIT 2:
The stacktrace says it all:
android.app.SuperNotCalledException: Activity {com.example.gpslocnav6ex/com.example.gpslocnav6ex.ShowMap} did not call through to super.onPause()
Call through to super.onPause() in your onPause()
#Override
public void onPause() {
super.onPause();
locationManager.removeUpdates(geoUpdateHandler);
}
Try this locationManager.removeUpdates(myLocationListener);
Your should write it in onPause()
#Override
protected void onPause()
{
// TODO Auto-generated method stub
super.onPause();
locationManager.removeUpdates(myLocationListener);
}
This will turn off GPS when your exit from your application .