Problem in getting location in android studio - java

I tried to get a latitude and longitude and the address of the current location.
When I tried in the emulator it worked..but when I tried to use my smartphone it was not working.
I have added the location permissions in the manifest.
Please help me with a solution.
The emulator I have used is Pixel 4a API 30.
I can't find where I have gone wrong.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView_location = findViewById(R.id.text_location);
button_location = findViewById(R.id.button_location);
//Runtime permissions
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this,new String[]{
Manifest.permission.ACCESS_FINE_LOCATION
},100);
}
button_location.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//create method
getLocation();
}
});
}
#SuppressLint("MissingPermission")
private void getLocation() {
try {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,5,MainActivity.this);
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(this, ""+location.getLatitude()+","+location.getLongitude(), Toast.LENGTH_SHORT).show();
try {
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
String address = addresses.get(0).getAddressLine(0);
textView_location.setText(address);
}catch (Exception e){
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}

Related

Am I missing something on retrieving GPS Current Location?

I recently began developing an app, and I've spent the last few days working on the GPS part to obtain the user's address.
The issue is that if I run the app in Android Studio Emulator and change the address on the map, it appears correctly on a Toast and in the String variable I created to store the address, as shown in the screenshot below, but if I build the APK and run it on a Smartphone, the Toast does not appear and the String variable remains empty.
Is there something in my code that I'm forgetting? I'll paste the code for someone to review below.
public class FragmentT1_Agora extends Fragment {
View view;
LocationManager locationManager;
String moradaAtual; // Current Address
private Button btEnviar;
public FragmentT1_Agora() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
view = inflater.inflate(R.layout.fragment_t1_agora, container, false);
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 100);
}
locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 3, mLocationListener);
return view;
}
private final LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Toast.makeText(getContext(), "" + location.getLatitude() + "," + location.getLongitude(), Toast.LENGTH_LONG).show();
try {
Geocoder geocoder = new Geocoder(getContext(), Locale.getDefault());
List<Address> moradas = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
moradaAtual = moradas.get(0).getAddressLine(0);
Toast.makeText(getContext(), "Morada: " + moradaAtual, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
}
I've left out the code that isn't related to the GPS.
Screenshot:

Cannot run android app in background through service

I try to get current location when the app running in background, so I use service. However, the data does not change in background, the service does not work. I want to know the problem. Here is the code of the app.
MainActivity as follow:
public class MainActivity extends Activity {
Button btn_start;
private static final int REQUEST_PERMISSIONS = 100;
boolean boolean_permission;
TextView tv_latitude, tv_longitude, tv_address,tv_area,tv_locality;
SharedPreferences mPref;
SharedPreferences.Editor medit;
Double latitude,longitude;
Geocoder geocoder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_start = (Button) findViewById(R.id.btn_start);
tv_address = (TextView) findViewById(R.id.tv_address);
tv_latitude = (TextView) findViewById(R.id.tv_latitude);
tv_longitude = (TextView) findViewById(R.id.tv_longitude);
tv_area = (TextView)findViewById(R.id.tv_area);
tv_locality = (TextView)findViewById(R.id.tv_locality);
geocoder = new Geocoder(this, Locale.getDefault());
mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
medit = mPref.edit();
btn_start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (boolean_permission) {
if (mPref.getString("service", "").matches("")) {
medit.putString("service", "service").commit();
Intent intent = new Intent(getApplicationContext(), GoogleService.class);
startService(intent);
} else {
Toast.makeText(getApplicationContext(), "Service is already running", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "Please enable the gps", Toast.LENGTH_SHORT).show();
}
}
});
fn_permission();
}
private void fn_permission() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
if ((ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION))) {
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION
},
REQUEST_PERMISSIONS);
}
} else {
boolean_permission = true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
boolean_permission = true;
} else {
Toast.makeText(getApplicationContext(), "Please allow the permission", Toast.LENGTH_LONG).show();
}
}
}
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
latitude = Double.valueOf(intent.getStringExtra("latitude"));
longitude = Double.valueOf(intent.getStringExtra("longitude"));
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
String cityName = addresses.get(0).getAddressLine(0);
String stateName = addresses.get(0).getAddressLine(1);
String countryName = addresses.get(0).getAddressLine(2);
tv_area.setText(addresses.get(0).getAdminArea());
tv_locality.setText(stateName);
tv_address.setText(countryName);
} catch (IOException e1) {
e1.printStackTrace();
}
tv_latitude.setText(latitude+"");
tv_longitude.setText(longitude+"");
tv_address.getText();
}
};
#Override
protected void onResume() {
super.onResume();
registerReceiver(broadcastReceiver, new IntentFilter(GoogleService.str_receiver));
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
}
Service as follow:
public class GoogleService extends Service implements LocationListener{
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
double latitude,longitude;
LocationManager locationManager;
Location location;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 1000;
public static String str_receiver =
"com.findmyelderly.findmyelderly.receiver";
Intent intent;
public GoogleService() {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(),5,notify_interval);
intent = new Intent(str_receiver);
// fn_getlocation();
}
#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) {
}
private void fn_getlocation() {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnable && !isNetworkEnable) {
} else {
if (isNetworkEnable) {
location = null;
try {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
if (isGPSEnable) {
location = null;
try {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
latitude = location.getLatitude();
longitude = location.getLongitude();
fn_update(location);
}
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
}
}
private class TimerTaskToGetLocation extends TimerTask {
#Override
public void run() {
mHandler.post(new Runnable() {
#Override
public void run() {
fn_getlocation();
}
});
}
}
private void fn_update(Location location){
intent.putExtra("latutide",location.getLatitude()+"");
intent.putExtra("longitude",location.getLongitude()+"");
sendBroadcast(intent);
}
}
build.gradle as follow
.........
compile 'com.android.support:appcompat-v7:25.0.0'
compile 'com.google.android.gms:play-services-location:10.0.1'
compile 'com.android.support:multidex:1.0.0'
AndroidManifest as follow
..........
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
.........
<service android:name=".GoogleService" android:exported="false" android:enabled="true"/>
</application>
</manifest>
I am very puzzled.
One thing you could try is to check the permissions of the app on the phone itself. I've found with my device (Android version 6.0.1) it's not enough to just add "uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> and
"uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />"
in the manifest, you have to grant permissions to the app manually on the device.
To do this, go to Settings > Apps > 'yourApp' > Permissions and slide across the bar to turn on Location for that app.
I'm new enough to Android apps myself so there may be a bigger problem in your case I'm not sure but worth a try anyway!

sometimes my app is Stuck on an old location and does not update

Hi I am developing android location tracker.I have developed two application one is for sending location of driver and other is for tracking the location of driver. Application is running well but sometimes my driver application's location is unable to connect with server and stuck on last location and doesnot reconnect().Sometimes it works perfect.Here is my code of driver app.
This is the screenshot of my tracking app which shows that driver app is stuck of last updated time after that it is not reconnecting.
private void setMapToCurrentLocation() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "First allow location permission", Toast.LENGTH_LONG).show();
return;
}
Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location != null) {
BusLocation busLocation = new BusLocation(location.getLatitude(), location.getLongitude(), 0, true, getCurrentTime());
mDatabase.child(String.valueOf(bus.getId())).setValue(busLocation);
moveMap(location);
}
}
#Override
protected void onStart() {
googleApiClient.connect();
super.onStart();
}
#Override
protected void onStop() {
googleApiClient.disconnect();
super.onStop();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
drawMarkers();
}
#Override
public void onConnected(#Nullable Bundle bundle) {
setMapToCurrentLocation();
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(final Location location) {
moveMap(location);
lastLocation = location;
float speed = Constants.convertSpeedToKMPH(location.getSpeed());
BusLocation busLocation = new BusLocation(location.getLatitude(), location.getLongitude(), speed, true, getCurrentTime());
mDatabase.child(String.valueOf(bus.getId())).setValue(busLocation);
textViewSpeed.setText(speed + " KMPH");
checkDistanceFromStop();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
public void onClick(View view) {
locationManager.removeUpdates(this);
}

Implementing a background service to catch location

I have an app that can capture fotos and send to the server.
I need to get location(lat,lon,alt) everytime i take a foto.
After a lot of research i understood that taking this data requires some time, the gps triangulation must run asyncronous, so i tried to figure out the best way to do this.
After some time, i had the idea, to start a service, everytime i run the aplication, this service will grab the last location everytime, and when i send a foto i will get the last location values.
So i did something like this(Service):
package com.example.afcosta.inesctec.pt.android.services;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
public class MyService extends Service {
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
private class LocationListener implements android.location.LocationListener
{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Log.e("asd", "onLocationChanged: " + location);
mLastLocation.set(location);
}
#Override
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(this.LOCATION_SERVICE);
}
}
}
and then i call the service when my app runs(at the moment i am testing this just with login(onCreate))
startService(new Intent(this, MyService.class));
i get this logTrace(with red):
`05-22 20:35:39.652 32426-32426/com.example.afcosta.inesctec.pt.android E/BOOMBOOMTESTGPS: LocationListener gps
05-22 20:35:39.652 32426-32426/com.example.afcosta.inesctec.pt.android E/BOOMBOOMTESTGPS: LocationListener network
05-22 20:35:39.652 32426-32426/com.example.afcosta.inesctec.pt.android E/BOOMBOOMTESTGPS: onCreate
05-22 20:35:39.652 32426-32426/com.example.afcosta.inesctec.pt.android E/BOOMBOOMTESTGPS: initializeLocationManager
05-22 20:35:39.657 32426-32426/com.example.afcosta.inesctec.pt.android E/BOOMBOOMTESTGPS: onStartCommand
CHANGES
that was what i tried to do before:
`
public class GoogleLocation implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private double lat;
private double lon;
private double alt;
public double getLat() {
return lat;
}
public void setLat(double lat) {
this.lat = lat;
}
public double getLon() {
return lon;
}
public void setLon(double lon) {
this.lon = lon;
}
public double getAlt() {
return alt;
}
public void setAlt(double alt) {
this.alt = alt;
}
boolean gps_enabled = false;
boolean network_enabled = false;
private Context context;
LocationManager lm;
LocationListener listener;
final int MY_PERMISSION_ACCESS_COURSE_LOCATION = 1;
public GoogleLocation(Context context) {
this.context = context;
}
public void getPosition() {
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
setLat(location.getLatitude());
setLon(location.getLongitude());
setAlt(location.getAltitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
location();
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) context, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION },
MY_PERMISSION_ACCESS_COURSE_LOCATION);
}
}
lm.requestLocationUpdates("gps", 5000, 0, listener);
}
public void location(){
GoogleApiClient googleApiClient = null;
if (googleApiClient == null) {
googleApiClient = new GoogleApiClient.Builder(context)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
googleApiClient.connect();
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30 * 1000);
locationRequest.setFastestInterval(1000);
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest);
//**************************
builder.setAlwaysShow(true); //this is the key ingredient
//**************************
PendingResult<LocationSettingsResult> result =
LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates state = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
// All location settings are satisfied. The client can initialize location
// requests here.
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
// Location settings are not satisfied. But could be fixed by showing the user
// a dialog.
try {
// Show the dialog by calling startResolutionForResult(),
// and check the result in onActivityResult().
status.startResolutionForResult(
(Activity) context, 1000);
} catch (IntentSender.SendIntentException e) {
// Ignore the error.
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
// Location settings are not satisfied. However, we have no way to fix the
// settings so we won't show the dialog.
break;
}
}
});
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}
`
i don't get any location, i don't know why, the onlocationchanged never runs, if the location doesn't change i want to get the last.
How can i accomplish that?
Thanks
Best regards
`
You don't need service class as you can get location in activity in which you are taking photos.
So first of all add permissions in manifest file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
and dependencies in gradle
compile 'com.google.android.gms:play-services:10.2.6'
Then in activity in which you are taking photos
Implement listeners
public class Activity extends AppCompatActivity implements ConnectionCallbacks, OnConnectionFailedListener{
protected Location mLastLocation;
private double Latitude;
private double Longitude;
in onCreate method ask user for location permission and call
buildGoogleApiClient();
and then define buildGoogleApiClient() method
/**
* Builds a GoogleApiClient. Uses the addApi() method to request the LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
after that implements listener interfaces methods
#Override
public void onConnected(Bundle connectionHint) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
Latitude = mLastLocation.getLatitude();
Longitude = mLastLocation.getLongitude();
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
#Override
public void onConnectionSuspended(int cause) {
// The connection to Google Play services was lost for some reason. We call connect() to
// attempt to re-establish the connection.
Log.i(TAG, "Connection suspended");
mGoogleApiClient.connect();
}
then at the end
#Override
protected void onStop() {
super.onStop();
if (mGoogleApiClient.isConnected()) {
mGoogleApiClient.disconnect();
}
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
let me know if you don't understand anything

onLocationChanged() isn't working properly

I'm trying to track users position and draw a path/his route on a map according to his movement (updatePolyline(), updateCamera(), updateMarker() are responsible for drawing a route). Program compiles, but the crucial error is that onLocationChanged() isn't called when location actually changes, thus, no path is beeing drawn.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap; // Might be null if Google Play services APK is not available.
private PolylineOptions mPolylineOptions;
LocationManager locationManager;
private LatLng mLatLng;
double latitude, longitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
setUpMapIfNeeded();
// LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
this.locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
// if(location != null) {
//
// onLocationChanged(location);
// }
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, this);
}
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
mLatLng = new LatLng(latitude, longitude);
runOnUiThread(new Runnable() {
#Override
public void run() {
updatePolyline();
updateCamera();
updateMarker();
}
});
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
#Override
public void onMapReady(GoogleMap map) {
mMap = map;
initializeMap();
}
private void updatePolyline() {
mMap.clear();
mMap.addPolyline(mPolylineOptions.add(mLatLng));
}
private void updateMarker() {
mMap.addMarker(new MarkerOptions().position(mLatLng));
}
private void updateCamera() {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mLatLng, 16));
}
private void initializeMap() {
mPolylineOptions = new PolylineOptions();
mPolylineOptions.color(Color.BLUE).width(10);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
LocationManager lm = null;
boolean gps_enabled = false, network_enabled = false;
if (lm == null)
lm = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (!gps_enabled && !network_enabled) {
AlertDialog.Builder dialog = new AlertDialog.Builder(MapsActivity.this);
dialog
.setTitle("No gps")
.setPositiveButton("Atšaukti", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
}
})
.setNegativeButton("Open settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
MapsActivity.this.startActivity(myIntent);
}
});
AlertDialog alert_dialog = dialog.create();
alert_dialog.show();
}
return false;
}
});
}
}
}

Categories