how to make my activity not stop working - android

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;
}

Related

How to get current coordinates/location in android

I've been working on trying to get the current location in android since several days but I didn't find a solution yet.
I know there are similar topics regarding this but in my case the code it didn't work. Is there anyone who has already solved this issue and can help me?
I add some tests I did.
Here's the GPS Tracker class.
package utility;
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 = 1; // 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;
// First get location from Network Provider
if (isNetworkEnabled) {
try {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
} catch (SecurityException e) {
}
Log.d("Network", "Network");
if (locationManager != null) {
try {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} catch (SecurityException e) {
}
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
try {
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 (SecurityException s) {
}
}
}
}
} 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) {
try {
locationManager.removeUpdates(GPSTracker.this);
} catch (SecurityException e) {
}
}
}
/**
* 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 Settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not active. Do you want to open?");
// 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;
}
}
And I instantiated this class in my activity, as follows:
import android.os.Bundle;
import android.app.Activity;
import android.widget.ImageButton;
import android.widget.TextView;
import utility.GPSTracker;
public class AroundMeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_around_me);
TextView location_text = (TextView) findViewById(R.id.location_text);
GPSTracker gps;
double latitude = 0.0;
double longitude = 0.0;
gps = new GPSTracker(AroundMeActivity.this);
// check if GPS enabled
if(gps.canGetLocation())
{
latitude = gps.getLatitude();
longitude = gps.getLongitude();
}
else
{
gps.showSettingsAlert();
}
location_text.setText(latitude + " " + longitude);
}
}
The results is 0.0 for both latitude and longitude.
Thank you in advance guys!!!
Use android LocationMannager
Checkout androidhive tutorial about Android GPS, Location Manager to get started
Here is a great library, very easy to use and lightweight: https://github.com/mrmans0n/smart-location-lib
Just compile it with gradle and thats' it.

Get geo locations repeatedly (after every.. 1 minute )

I am calling toast message in AndroidGPSTrackingActivity.class. how to fetch geo locations after every 1 minutes.. With below code I am getting only once
public class AndroidGPSTrackingActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText( getApplicationContext(),"Your Locion is - \nLat: " + latitude
+ "\nLog: " + longitude, Toast.LENGTH_LONG).show();
System.out.println("respmaillati::;;"+latitude);
} else {
gps.showSettingsAlert();
}
}
in manifest I given
<service android:name=".GPSTracker" />
Code:
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 = 100 * 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;
// 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();
}
System.out.println("responsel:::"+latitude);
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
System.out.println("responsel:::"+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;
}
}
Try this!
Wrap the toast code in a method and call it recursively using Handler and Runnable:
public class AndroidGPSTrackingActivity extends Activity {
Handler showLocationHandler;
Runnable showLocationRunnable;
private static final int DELAY_TIME = 1000 * 60; //delay time - 1 minute
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
showLocationHandler = new Handler();
showLocationRunnable = new Runnable() {
#Override
public void run() {
showLatLongToast();
}
};
//call the method once
showLatLongToast();
}
public void showLatLongToast() {
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Locion is - \nLat: " + latitude
+ "\nLog: " + longitude, Toast.LENGTH_LONG).show();
System.out.println("respmaillati::;;" + latitude);
} else {
gps.showSettingsAlert();
}
//call the same method after some delay
showLocationHandler.postDelayed(showLocationRunnable, DELAY_TIME);
}
#Override
protected void onDestroy() {
super.onDestroy();
//kill this runnable when ever you want to stop displaying toast like this
showLocationHandler.removeCallbacks(showLocationRunnable);
}
}

How to display automatic longitude and latitude location after every 1 minute with out clicking a button

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;
}
}
The above code is for gps tracking class and following code is the activity code
public class GPSTrackingActivity extends Activity {
Button showLocation1;
// GPSTracker class
GPStracker gps;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gpstracking);
showLocation1 = (Button) findViewById(R.id.showlocation1);
// show location button click event
showLocation1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPStracker(GPSTrackingActivity.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();
}
}
});
You can use handlers and post delayed
handler=new Handler();
Runnable r=new Runnable() {
public void run() {
//Do your things
//Below line recursively posts for every minute
handler.postDelayed(r,1000*60);
}
};
handler.post(r);
Put below code in your activity class.
double latitude, longitude;
Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run()
{
latitude = gps.getLatitude();
longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
handler.postDelayed(runnable, 1000);
}
};
handler.postDelayed(runnable, 3000);

how to run locationlistener in background

I would like to run a locationlistener on my app, that send after every 10m or every 5 seconds an new "Popup". Later I will send my data to the cloud.
This is my GPSTracker class:
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;
import android.widget.Toast;
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 * 5 * 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) {
Toast.makeText(GPSTracker.this,"Provider enabled by the user. GPS turned on",Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
For my activityclass I have made this:
gps = new GPSTracker(MainActivity.this);
double latitude2 = gps.getLatitude();
double longitude2 = gps.getLongitude();
I receive the data, this works. But now I want to run the data in the background so when the location is changed I can implement a function that sends my data to the cloud.
I tried this:
private void startGPSTrackerInBackground() {
new AsyncTask<Void,Void,String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "This message runs in background";
gps = new GPSTracker(MainActivity.this);
if(!gps.canGetLocation()){
gps.showSettingsAlert();
}else{
gps = new GPSTracker(MainActivity.this);
double latitude2 = gps.getLatitude();
double longitude2 = gps.getLongitude();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
}
But in this function it's not possible to get the information of my GPSTracker class, anyone an idea to make this possible?
Create an independent class, add a GPSTracker member variable and pass it in the constructor. Wrap your task in a method you can invoke later:
public class BackgroundGPSTracker() {
GPSTracker tracker;
public BackgroundGPSTracker(GPSTracker tracker) {
this.tracker = tracker;
}
public void run() {
new AsyncTask<Void,Void,String>() {
#Override
protected String doInBackground(Void... params) {
// Do some background stuff.
}
#Override
protected void onPostExecute(String msg) {
// Do after work stuff
}
}.execute(null, null, null);
}
}
Use:
If you create GPSTracker like this:
gps = new GPSTracker(MainActivity.this);
Then you start the activity passing it to the task:
BackgroundGPSTracker bgGPSTracker= new BackgroundGPSTracker(gps);
bgGPSTracker.run();
EDIT
Use a member variable to store last known location, and timer to schedule updates:
public class CampaignsDiscoverActivity extends Activity{
static final int QUERY_CAMPAINGS_DELAY = 30000;// milliseconds
Location currentLocation;
Timer timer;
void restartTimer() {
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
sendDataToServerOrWhatever();
}
}, QUERY_CAMPAINGS_DELAY, QUERY_CAMPAINGS_DELAY);
}
void stopTimer() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
void sendDataToServerOrWhatever() {
// Do some stuff using currentLocation
}
Set a listener for locations changes. when location changed is raised, stop the timer, do work and restart it:
void startGPSUpdates() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(Location location) {
stopTimer();
currentLocation = location;
sendDataToServerOrWhatever();
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
// Initialize location.
currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (currentLocation == null) {
currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
restartTimer();
}
To start the system just invoke startGPSUpdates.
You should pause listeners when app goes to the background and resume when foreground:
#Override
public void onPause() {
super.onPause();
if (applicationData.isLoggedIn()) {
pauseLocationUpdates();
}
}
#Override
public void onResume() {
super.onResume();
if (applicationData.isLoggedIn()) {
resumeLocationUpdates();
}
}
void pauseLocationUpdates() {
locationManager.removeUpdates(locationListener);
}
void resumeLocationUpdates() {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
I think you should do the same with the timer, but the app where I'm using it is not finished and fully tested yet, so you might find bugs.
Hope that helps.

GPS Location not being changed android

I'm writing a simple app that needs to set the current GPS coordinates from let's say point A, then travel to another point B and have it detect the coordinates at point B. I am able to get point A coordinates no problem. I'm just not getting it to detect the coordinates at point B, it reads the same coordinates as the ones at point A. I've got the app installed on my phone, and I am driving a mile between points. My manifest file includes every possible permission for location.
Here is the activity code.
public class GPSTrackingActivity extends Activity {
Button btnShowLocation;
Button btnShowEndLocation;
// GPSTracker class
GPSTracker gps;
TextView tvIntialLocation;
TextView tvEndLocation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myDBHelper = new DataBaseHelper(GPSTrackingActivity.this);
tvIntialLocation = (TextView)findViewById(R.id.tvIntialLocation);
tvEndLocation = (TextView)findViewById(R.id.tvEndLocation);
// create class object
gps = new GPSTracker(GPSTrackingActivity.this);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
btnShowEndLocation = (Button)findViewById(R.id.btnEndLocation);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
tvIntialLocation.setText("Start Location is - \nLat: " + latitude + "\nLong: " + longitude);
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
// show location button click event
btnShowEndLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
tvEndLocation.setText("End Location is - \nLat: " + latitude + "\nLong: " + longitude);
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
}
Here is the class setting up the GPS Tracker class. I am not sure if the onLocationChanged is getting called, I didn't see any Toast messages when the location changed while I was driving.
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;
// 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;
}
/**
* 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) {
location = getLocation();
// Testing onLocationChanged:
String hej1 = Double.toString(location.getLatitude());
String hej2 = Double.toString(location.getLongitude());
Toast.makeText(this, "Location: "+"Lat: " + hej1 + "Long: " + hej2,
Toast.LENGTH_LONG).show();
}
/**
* 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();
}
}
Why is the second point not being updated to the current location? Start and End points show as the same GPS coordinates.
Change the onLocationChanged to the code below
#Override
public void onLocationChanged(Location location) {
this.location = location;
// Testing onLocationChanged:
String hej1 = Double.toString(location.getLatitude());
String hej2 = Double.toString(location.getLongitude());
Toast.makeText(this, "Location: "+"Lat: " + hej1 + "Long: " + hej2,
Toast.LENGTH_LONG).show();
}
You should prefix class members with m for example Location mLocation;
You are using getLastKnownLocation that always does not work for getting update location.
I had same problem. Finally i solved it. You can use google FusedLocationApi for getting location update like google map app.
Code Sample in service:
#Override
public void onCreate() {
if (checkPlayServices()) {
startFusedLocation();
registerRequestUpdate(this);
}
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
Toast.makeText(getApplicationContext(),
"This device is supported. Please download google play services", Toast.LENGTH_LONG)
.show();
} else {
Toast.makeText(getApplicationContext(),
"This device is not supported.", Toast.LENGTH_LONG)
.show();
}
return false;
}
return true;
}
public void startFusedLocation() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API)
.addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
#Override
public void onConnectionSuspended(int cause) {
}
#Override
public void onConnected(Bundle connectionHint) {
}
}).addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
#Override
public void onConnectionFailed(ConnectionResult result) {
}
}).build();
mGoogleApiClient.connect();
} else {
mGoogleApiClient.connect();
}
}
public void stopFusedLocation() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
}
public void registerRequestUpdate(final LocationListener listener) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000); // every second
//mLocationRequest.setFastestInterval(NOTIFY_INTERVAL/2);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
try {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, listener);
} catch (SecurityException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
if (!isGoogleApiClientConnected()) {
mGoogleApiClient.connect();
}
registerRequestUpdate(listener);
}
}
}, 1000);
}
public boolean isGoogleApiClientConnected() {
return mGoogleApiClient != null && mGoogleApiClient.isConnected();
}
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lon = location.getLongitude();
Toast.makeText(getApplicationContext(), "NEW LOCATION RECEIVED", Toast.LENGTH_LONG).show();
String Provider=location.getProvider();
Log.d("location", "IN ON LOCATION CHANGE, lat=" + lat + ", lon=" + lon);
//locationManager.removeUpdates(this);
}
public void setFusedLatitude(double lat) {
fusedLatitude = lat;
}
public void setFusedLongitude(double lon) {
fusedLongitude = lon;
}
public double getFusedLatitude() {
return fusedLatitude;
}
public double getFusedLongitude() {
return fusedLongitude;
}

Categories

Resources