I've followed this tutorial for GPS tracking in Android application with this class:
GPSTracker.java
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} 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.d("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/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "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;
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
and this is the Activity using the previous class:
AndroidGPSTrackingActivity.java
package com.example.gpstracking;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AndroidGPSTrackingActivity extends Activity {
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
}
How can I receive new position updates from the AndroidGPSTrackingActivity.java ?
How can I get latitude and longitude in AndroidGPSTrackingActivity taken by onLocationChanged that is in GPSTracker class ?
many thanks
I can't write comments yet, so I try here:
I would create a Handler in your Activity and assign it to the the GPSTracker Class:
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// new GPS Informations
// get it by gps.getLatitude() for example
};
};
gps = new GPSTracker(AndroidGPSTrackingActivity.this, handler);
In your GPSTracker Class you have to change the constructor of course:
Handler mHandler;
public GPSTracker(Context context, Handler handler){
...
this.mHandler = handler;
}
And then, just send the info, that the location has changed to your activity:
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
mHandler.sendEmptyMessage(0);
}
Related
I am trying to show my latitude and longitude as I move around, but it stays at one value and does not change. Can someone tell me what is wrong with my code? I have already updated the manifest file as well so I'm not sure why it's not working properly. I make calls to it in a writeToFile method in my main activity.
package com.explorer.extractor;
import android.app.Service;
import android.content.Context;
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.util.Log;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
//flag for GPS status
boolean isGPSEnabled = false;
//flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; //location
double latitude; //latitude
double longitude; //longitude
//The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; //10 meters
//The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 0; //0 minute
//Declare a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
//no network provider is enabled
} 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);
Log.i("NETWORK", "NUMBER 1");
if (location != null) {
Log.i("NETWORK", "is this not null");
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.i("NETWORK", "THE LATITUDE IS " + latitude);
}
}
}
//if GPS Enabled get lat/long usig GPS services
else if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
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;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public IBinder onBind(Intent arg0) {
return null;
}
//Function to get Latitude
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
//Function to get longitude
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
Log.i("long", "the long is " + longitude);
}
Log.i("long", "the long isnt working");
return longitude;
}
/**
* Function to check if best network provider
*
* #return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Stop Using GPS Listener
* Calling this function stops using GPS in app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
}
You should be using onLocationChanged() to update the Lat Longs. With that empty, I'm not sure how often you are actually updating your UI
This the Service class that I'm trying to use from my MainActivity.java. Running on emulator.
package com.example.sonia.project;
import android.app.Service;
import android.content.Context;
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.util.Log;
public class GPSTracker extends Service implements LocationListener {
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker() {
}
public Location getLocation(Context mContext) {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} 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.d("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/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "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;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
#Override
public void onLocationChanged(Location location) {
Log.d("Location", "Location changed!");
this.location = location;
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
This is my onStart() method of MainActivity
#Override
protected void onStart() {
super.onStart();
gps = new GPSTracker();
gps.getLocation(this);
}
And then I call getLocation() again on a button click in MainActity
gps.getLocation(this);
The accepted answer on this question suggests getting location updates and using multiple providers - My current location always returns null. How can I fix this?. I'm doing both.
getLocation() always returns a null location, even if I try to get the location after several minutes. What can do to make it return a valid location and not null?
To get Location in emulator you have to configure through emulator control
For more information refer following link
http://wptrafficanalyzer.in/blog/android-gps-with-locationmanager-to-get-current-location-example/
I am trying to get Current Location using either GPS or Network Provider. My device's GPS is enabled but I'm not getting Latitude and Longitude.
GpsTracker.java:
public class GpsTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS Status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
public double latitude;
public double longitude;
// The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10
// metters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GpsTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// if Network Provider Enabled get lat/long using GPS Services
if (isNetworkEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "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();
Log.e("Error : Location",
"Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
}
Service.Java
public class WifiScaningService extends IntentService {
GpsTracker gpsTracker;
double latitude;
double longitude;
public WifiScaningService() {
super("WifiScaningService");
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
Log.e("service call","service call");
}
#Override
protected void onHandleIntent(Intent intent) {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
gpsTracker = new GpsTracker(this);
String stringLatitude = String.valueOf(gpsTracker.latitude);
latitude = Double.parseDouble(stringLatitude);
Log.e("Latitude",stringLatitude);
String stringLongitude = String.valueOf(gpsTracker.longitude);
longitude = Double.parseDouble(stringLongitude);
Log.e("Longitude",stringLongitude);
return START_STICKY;
}
}
I have included necessary permissions in AndroidManifest.xml file. Required to show current location.
<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"/>
MainActivity:
import android.location.Address;
import android.location.Location;
import com.example.havadurumumenu.MyLocationManager.LocationHandler;
public class MainActivityextends Activity implements LocationHandler{
public MyLocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
currentLocation();
}
});
}
public void currentLocation(){
locationManager = new MyLocationManager();
locationManager.setHandler(this);
boolean isBegin = locationManager.checkProvidersAndStart(getApplicationContext());
if(isBegin){
//if at least one of the location providers are on it comes into this part.
}else{
//if none of the location providers are on it comes into this part.
}
}
#Override
public void locationFound(Location location) {
Log.d("LocationFound", ""+location);
//you can reach your Location here
//double latitude = location.getLatitude();
//double longtitude = location.getLongitude();
locationManager.removeUpdates();
}
#Override
public void locationTimeOut() {
locationManager.removeUpdates();
//you can set a timeout in MyLocationManager class
txt.setText("Unable to locate. Check your phone's location settings");
}
MyLocationManager:
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
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.os.Handler;
import android.os.Message;
/*---------- Listener class to get coordinates ------------- */
public class MyLocationManager implements LocationListener {
public LocationManager locationManager;
public LocationHandler handler;
private boolean isLocationFound = false;
public MyLocationManager() {}
public LocationHandler getHandler() {
return handler;
}
public void setHandler(LocationHandler handler) {
this.handler = handler;
}
#SuppressLint("HandlerLeak")
public boolean checkProvidersAndStart(Context context){
boolean isBegin = false;
Handler stopHandler = new Handler(){
public void handleMessage(Message msg){
if (!isLocationFound) {
handler.locationTimeOut();
}
}
};
stopHandler.sendMessageDelayed(new Message(), 15000);
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 1000, this);
isBegin = true;
}
if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 1000, this);
isBegin = true;
}
return isBegin;
}
public void removeUpdates(){
locationManager.removeUpdates(this);
}
/**
* To get city name from coordinates
* #param location is the Location object
* #return city name
*/
public String findCity(Location location){
/*------- To get city name from coordinates -------- */
String cityName = null;
Geocoder gcd = new Geocoder(AppController.getInstance(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
cityName = addresses.get(0).getLocality();
}
catch (IOException e) {
e.printStackTrace();
}
return cityName;
}
#Override
public void onLocationChanged(Location loc) {
isLocationFound = true;
handler.locationFound(loc);
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
public interface LocationHandler{
public void locationFound(Location location);
public void locationTimeOut();
}
}
Also add all the permissions below in your Manifest.xml
<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" />
I Solved by exchanging position of both methods.
First app trying to get location using GPS if GPS is not enabled then using network provider method.
public class GpsTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS Status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
public double latitude;
public double longitude;
// The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10
// metters
// The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GpsTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if Network Provider Enabled get lat/long using GPS Services
if (isNetworkEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
}
}
} catch (Exception e) {
// e.printStackTrace();
Log.e("Error : Location",
"Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
}
I developed app that getting GPS data and send to Server. So i want to get GPS data while my app is running background in Android device. I have search in many websites, but i could not answer.
I use 2 class. One of them is Main class and another is GPSTracker class. Now i give some part code of 2 class.
Main Class
public class Request extends Activity {
public static Float longitude;
public static Float latitude;
public static int ID;
public static String URL="http://xxx.xxx";
GPSTracker gps;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
final Button button_send_info = (Button)findViewById(R.id.button_send_info);
final TextView show_infos = (TextView) findViewById (R.id.textView1);
gps = new GPSTracker(Request.this);
if(gps.canGetLocation()){
latitude = (float) gps.getLatitude();
longitude = (float) gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
if( Build.VERSION.SDK_INT >= 8){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
button_send_info.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("latitude", latitude.toString()));
postParameters.add(new BasicNameValuePair("longitude", longitude.toString()));
String response = null;
try
{
response = CustomHttpClient.executeHttpPost(URL, postParameters);
String res=response.toString();
show_infos.setText(res);
}
catch (Exception e)
{
//hata alanı
}
}
});
GPSTracker Class;
public class GPSTracker extends Service implements LocationListener {
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("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/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "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;
}
How can i do it?
There is a component called Service in android. It provides background activity. You can perform background process in it. Service has no GUI. You can write a GPS fetching code there.
Have a look at simple tutorial of Service components from Vogella.
import android.app.Activity;
public class LocationTracking extends Activity {
Button btnShowLocation;
Button refresh;
GPSTracker gps;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_tracking);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
refresh = (Button) findViewById(R.id.refresh);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(LocationTracking.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
((TextView)findViewById(R.id.latitude)).setText(Double.toString(latitude));
((TextView)findViewById(R.id.longitude)).setText(Double.toString(longitude));
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
refresh.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((TextView)findViewById(R.id.latitude)).setText("");
((TextView)findViewById(R.id.longitude)).setText("");
}
});
}
}
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 mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("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/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "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;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
i found this gps tracking activity on the net i tried it already and it works perfectly but i encountered a problem later on.when i start a new activity it stop on running what i want to do is for it not to stop even if i start i new activity example if someone is calling or im texting the gps tracking will still track my location where did i make my mistake?
use this code, registered the LocationManager in onchangeLocation() method.
public class NewLocationListener implements android.location.LocationListener {
private final static String TAG = "LocationListener";
private Context context = null;
private LocationManager locationManager = null;
private double latitude = 0.0;
private double longitude = 0.0;
/*public String newlatitude=null;
public String newlongitude=null;*/
private Location gpslocation=null;
public void setDefault() {
Log.v(TAG + ".setDefault", "GPS Co-ordinates initialised");
latitude = 0.0;
longitude = 0.0;
}
public NewLocationListener(Context ctx) {
Log.v(TAG + ".LocationListener", "LocationListener constructor called");
context = ctx;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
public void onProviderDisabled(String provider) {
Log.v(TAG + ".onProviderDisabled", "onProviderDisabled method called");
}
public void onProviderEnabled(String provider) {
Log.v(TAG + ".onProviderEnabled", "onProviderEnabled method called");
}
public void onLocationChanged(Location location) {
gpslocation=location;
Log.v(TAG + ".onLocationChanged", "onLocationChanged method called");
//Toast.makeText(context, "onLocationChanged called", Toast.LENGTH_SHORT).show();
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (gpslocation != null) {
setLocationCoordinates(gpslocation);
} else {
Log.v(TAG + ".onLocationChanged", "couldn't get gps using onLocationChange");
getLastKnownLocation();
}
}
public void setLocationCoordinates(Location location) {
try {
double latNew = (location.getLatitude());
double lonNew = (location.getLongitude());
if (latNew != 0.0 && lonNew != 0.0) {
Log.v(TAG + ".onLocationChanged", "New location co-ordinates are not 0");
/* setLatitude(latNew);
setLongitude(lonNew);*/
/*
* latitude = latNew; longitude = lonNew;
*/
String newlatitude=Double.toString(latNew);
String newlongitude=Double.toString(lonNew);
Log.v(TAG, "new latitude is" + newlatitude+" new longitude is" + newlongitude);
//Toast.makeText(context, "lat: " + newlatitude+" lon: " + newlongitude, Toast.LENGTH_SHORT).show();
} else {
//Toast.makeText(context, "we got 0.0 value ", Toast.LENGTH_SHORT).show();
Log.v(TAG + ".onLocationChanged", "we got 0.0 value ");
}
} catch (Exception e) {
Log.v(TAG + ".onLocationChanged.Exception", "Exception is " + e);
}
}
public void getLastKnownLocation() {
Location location = locationManager.getLastKnownLocation(getBestProvider());
gpslocation=location;
if (gpslocation != null) {
//Toast.makeText(context, "LastKnownLocation called", Toast.LENGTH_SHORT).show();
setLocationCoordinates(gpslocation);
} else {
//Toast.makeText(context, "couldn't get LastKnownLocation", Toast.LENGTH_SHORT).show();
Log.v(TAG + ".onLocationChanged","couldn't get gps using lastKnownLocation");
}
}
public String getBestProvider() {
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
String bestProvider = locationManager.getBestProvider(criteria, true);
return bestProvider;
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.v(TAG + ".onStatusChanged", "onStatusChanged method called");
}
public double getLatitude() {
if (gpslocation != null) {
latitude = gpslocation.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (gpslocation != null) {
longitude = gpslocation.getLongitude();
}
return longitude;
}