get current location lat and lng on map ready - java

i want to get current location and move camera to current location and then save current location(LatLng) to my database
i get ACCESS_FINE permission
and use following code, but application has stop working
double lat = map.getMyLocation().getLatitude();
double lng = map.getMyLocation().getLongitude();
LatLng cur = new LatLng(lat,lng);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(cur, 17));
android log cat :
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference

getMyLocation(), this method is deprecated.
Try this:
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager
.getBestProvider(criteria, false));
double latitude = location.getLatitude();
double longitude = location.getLongitude();

getting current location from map.getMyLocation() is not best way to get current location. you can use this class for finding user current location
public class LocationFinder {
private Timer timer;
private LocationManager locationManager;
private LocationResult locationResult;
private boolean gpsEnabled = false;
private boolean networkEnabled = false;
public boolean getLocation(Context context, LocationResult result) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
locationResult = result;
if (locationManager == null)
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
try {
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gpsEnabled && !networkEnabled)
return false;
if (gpsEnabled)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0.0F, locationListenerGps);
if (networkEnabled)
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0.0F, locationListenerNetwork);
timer = new Timer();
timer.schedule(new GetLastLocation(), 20000L);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer.cancel();
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer.cancel();
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
locationManager.removeUpdates(locationListenerGps);
locationManager.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if (gpsEnabled)
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (networkEnabled)
net_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if (gps_loc != null) {
locationResult.gotLocation(gps_loc);
return;
}
if (net_loc != null) {
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
}

Related

Have latitude and longitude in a service return 0.0

I am a beginner in Android application development. I will get latitude and longitude from GPSTracker.class every 5 minutes for send to SQLite DB in next step but when I call GPSTracker.class
It's return latitude = 0.0 and longitude = 0.0 too
help me please
This is my code
AppService.class
public class AppService extends Service {
private MyThread thread;
PowerManager.WakeLock wl;
double latitude;
double longitude;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
thread = new MyThread();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!thread.isAlive()) {
thread.start();
}
return START_STICKY;
}
private class MyThread extends Thread {
private static final String tag = "Sevice Demo";
private static final int delay = 300000;
private int roundNumber = 0;
private boolean finishService = false;
#Override
public void run() {
while (true) {
PowerManager pm = (PowerManager) getApplicationContext().getSystemService(
getApplicationContext().POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
wl.release();
GPSTracker gps = new GPSTracker(AppService.this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
Log.d("dddd",String.valueOf(latitude)+" & "+String.valueOf(longitude));
try {
sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (finishService) {
return;
}
}
}
}
#Override
public void onDestroy() {
Toast.makeText(this, "Service Stop...", Toast.LENGTH_LONG).show();
if (thread.isAlive()) {
stopService(new Intent(this, AppService.class));
}
super.onDestroy();
}
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location locations;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// get GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// get network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
//return TODO;
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
}
if (locationManager != null) {
locations = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (locations != null) {
latitude = locations.getLatitude();
longitude = locations.getLongitude();
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (locations == 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) {
locations = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (locations != null) {
latitude = locations.getLatitude();
longitude = locations.getLongitude();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return locations;
}
public double getLatitude() {
if (locations != null) {
latitude = locations.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (locations != null) {
longitude = locations.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
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) {
}
}
}
The fused location provider is a location API in Google Play services that intelligently combines different signals to provide the location information that your app needs.
The fused location provider manages the underlying location technologies, such as GPS and Wi-Fi, and provides a simple API that you can use to specify the required quality of service. For example, you can request the most accurate data available, or the best accuracy possible with no additional power consumption.
Last Known Location
Receiving Location Updates
This code
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
locations = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (locations != null) {
latitude = locations.getLatitude();
longitude = locations.getLongitude();
}
}
needs to be refactored. When you call LocationManager.requestUpdates() you are asking the LocationManager to call your app back when there is an update to the GPS position. This will happen at some later time (in the future), depending on how long it takes for the phone to determine its position using GPS. The call to LocationManager.getLastKnownLocation() will only return the last "known" location, which it doesn't have yet.
Once you have requested location updates, Your app will be called back with GPS data. The framework will call the method onLocationChanged(). You currently have no code in that method, so you won't do anything when the method is called.

Android GPS_PROVIDER always returns null

I'm developing an app and when I try to get the location of Android, I always get null.
I try this with a real device, running API 19 and with the GPS enabled
This is my code:
double latitud, longitud;
Location location;
LocationManager mlocManager;
LocationListener locationListener;
String provider;
final boolean gpsEnabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!gpsEnabled) {
Intent settingsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(settingsIntent);
}
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION,}, 1000);
return;
}
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = mlocManager.getBestProvider(criteria, true);
Log.i("PROVIDER", provider);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
latitud = location.getLatitude();
longitud = location.getLongitude();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
mlocManager.requestLocationUpdates(provider, 0, 0,locationListener);
location = mlocManager.getLastKnownLocation(provider);
if (location != null) {
latitud = location.getLatitude();
longitud = location.getLongitude();
Log.i("LATITUD GPS", String.valueOf(latitud));
Log.i("LONGITUD GPS", String.valueOf(longitud));
} else {
Log.e("LOCATION", "null");
}
}
I tried to use LocationManager.GPS_PROVIDER instead of Criteria, but it doesn't work.
Thanks in advance.

Android Wear App java.lang.OutOfMemoryError: Failed to allocate

I had a problem. I want to make an Android App for my Android Wear device. I want to get the latitude and longitude of my current location. But when I run the applicatie I got this error:
03-22 11:14:00.096 29013-29013/? E/AndroidRuntime: Error reporting crash
java.lang.OutOfMemoryError: Failed to allocate a 52435096 byte allocation with 2097152 free bytes and 32MB until OOM
at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95)
at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:125)
at java.lang.StringBuffer.append(StringBuffer.java:278)
at java.io.StringWriter.write(StringWriter.java:123)
at com.android.internal.util.FastPrintWriter.flushLocked(FastPrintWriter.java:358)
at com.android.internal.util.FastPrintWriter.appendLocked(FastPrintWriter.java:303)
at com.android.internal.util.FastPrintWriter.write(FastPrintWriter.java:625)
at com.android.internal.util.FastPrintWriter.append(FastPrintWriter.java:658)
at java.io.PrintWriter.append(PrintWriter.java:691)
at java.io.PrintWriter.append(PrintWriter.java:687)
at java.io.Writer.append(Writer.java:198)
at java.lang.Throwable.printStackTrace(Throwable.java:324)
at java.lang.Throwable.printStackTrace(Throwable.java:300)
at android.util.Log.getStackTraceString(Log.java:343)
at com.android.internal.os.RuntimeInit.Clog_e(RuntimeInit.java:61)
at com.android.internal.os.RuntimeInit.-wrap0(RuntimeInit.java)
at com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:86)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
at java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
This is my code:
MainActivity.java
public class MainActivity extends Activity {
private TextView tvHuidigeLocatie;
private Button btSetHuidigeLocatie;
GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
onClickInfoButtonListener();
}
});
}
private void onClickInfoButtonListener() {
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
tvHuidigeLocatie = (TextView) stub.findViewById(R.id.tvHuidigeLocatie);
btSetHuidigeLocatie = (Button) stub.findViewById(R.id.btnSetHuidigeLocatie);
btSetHuidigeLocatie.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick(View v){
gps = new GPSTracker(MainActivity.this);
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
tvHuidigeLocatie.setText("" + latitude + ", " + longitude);
}else{
gps.showSettingsAlert();
}
}
}
);
}
}
GPSTracker.java
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 = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
if ( Build.VERSION.SDK_INT >= 23 &&
ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return location;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
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;
}
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 showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS in settings");
alertDialog.setMessage("GPS staat niet aan, Wilt u naar uw instellingen gaan?");
alertDialog.setPositiveButton("Instellingen", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Annuleer", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
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;
}
}
I hope anyone see the problem and can help me with this problem.
android:largeHeap="true"
In your android manifest, hope this will solve your problem.
http://developer.android.com/guide/topics/manifest/application-element.html#largeHeap

Lat/lgn return 0

I'm currently working on a project for school. I have to use location service. I have a marker problem. I can locate myself on the map with a small point from google (I think), but the marker is always on 0,0. If my logic is good, the getLatitude() and the getLongitude() return NULL. I've follow a tutorial for the code.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
GPSTracker gps;
//ImageItem imgItem;
double lat;
double longi;
double latitude;
double longitude;
String adresse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
laCreation();
}
public void laCreation() {
gps = new GPSTracker(MapsActivity.this);
if (gps.canGetLocation()==true) {
latitude = gps.getLatitude();
longitude = gps.getLongitude();
lat = latitude;
longi = longitude;
} else {
gps.showSettingsAlert();
}
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mMap = mapFragment.getMap();
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
mMap.setMyLocationEnabled(true);
LatLng position = new LatLng(lat, longi);
mMap.addMarker(new MarkerOptions().position(position).title("Vous : "+ latitude + ","+longitude +"," +adresse));//new LatLng(lat,longi)
mMap.moveCamera(CameraUpdateFactory.newLatLng(position));
}
public void onMapReady(GoogleMap googleMap) {}
}
Here is my GPSTracker :
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 = 10; //10m avant update gps
private static final long MIN_TIME_BW_UPDATES = 2000; //2 sec avant uptade gps
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
onLocationChanged(location);
if (isGPSEnabled) { 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();
if (latitude ==0){showSettingsAlert();}
}
}
}
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
if (latitude ==0){showSettingsAlert();}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if (locationManager != null) {
}
locationManager.removeUpdates(GPSTracker.this);
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
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 showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS en cours de configuration");
alertDialog.setMessage("GPS non valide. Voulez-vous aller dans le menu de configuration?");
alertDialog.setPositiveButton("Configuration", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
I'm French, sorry for my bad English
You should utilize method
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, location.getLatitude()+"-"+longitude = location.getLongitude());
// TODO Auto-generated method stub
}
for getting latitude and longitude. First time it will get definitely call and then it will be call and then as soon as location gets changed.
If you force fully asking for latti and longi their are chances OS is not having anything s it would return 0,0.
One way more ask for last known location using GoogleFuseLocationApi
public class SpotRecognistionService extends Service {
private static final String TAG = SpotRecognistionService.class.getSimpleName();
public static final String NOTIFICATION = "location.track.services.receiver";
//Google Api Client for Location
private GoogleApiClient mGoogleApiClient;
// private Location mLastLocation;
private LocationRequest mLocationRequest;
private GPSLocationListener gpsLocationListener;
#Override
public IBinder onBind(Intent intent) {
return null;
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(gpsLocationListener)
.addOnConnectionFailedListener(gpsLocationListener)
.addApi(LocationServices.API)
.build();
}
#Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service creating");
gpsLocationListener = new GPSLocationListener();
buildGoogleApiClient();
//Connect to get Location
mGoogleApiClient.connect();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "Service destroying");
if (mGoogleApiClient != null && mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
}
private class GPSLocationListener implements LocationListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
//Update Result
publishResults(location.toString(), 1);
}
private void publishResults(String lat_Long, int result) {
Log.i(TAG, lat_Long);
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(10000);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
reConnect();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
reConnect();
}
public void reConnect() {
if (mGoogleApiClient != null && !mGoogleApiClient.isConnected())
mGoogleApiClient.connect();
}
}
}

Location Menager - Location Updates

So I'm trying to update the current location of a user every 5 seconds using a locationMenager, but it's not working. Here the code:
GPSTracker.java
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 = 10;
private static final long MIN_TIME_BW_UPDATES = 5000;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
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;
}
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 showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
As you can see it is set to update. And this is the onCreate() in SearchActivity.java
gps = new GPSTracker(SearchActivity.this);
if (gps.canGetLocation()) {
ParseUser user2 = ParseUser.getCurrentUser();
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
geoPoint = new ParseGeoPoint(latitude, longitude);
user2.put("lat_long", geoPoint);
textView.setText(latitude+" "+longitude);
user2.saveInBackground();
} else {
gps.showSettingsAlert();
}
So if I put the code above in a onClick method it works, it updates the current location. I've tried to implement it with a TimerTask but the location ends up being (0, 0). So does anyone know what I can do here? Because what preferably I would like to make a On/Off switch for the location, make it run in background if possible, but first I would like to resolve the issue with the Location Updates.
#Override
public void onLocationChanged(Location location) {
this.location = location;
getLatitude();
getLongitude();
ParseUser user2 = ParseUser.getCurrentUser();
ParseGeoPoint geoPoint = new ParseGeoPoint(getLatitude(), getLongitude());
user2.put("lat_long", geoPoint);
user2.saveInBackground();
}
Okay so this was the answer, just had to change the onLocationChanged.

Categories

Resources