hello i wanna create a attandace online using getlocation
everything works fine until i close the app and forget to turn on the GPS service
everytime i open activity to get geoLocation code is always failed ,
what i ask is how can in get current location using google maps api so everytime i open the apps is works to get location geocodes
Please Help Im struggle to solve this i need this app for my final project
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.sistemabsensi.online.Absensi.onConnected(Absensi.java:415)
at com.google.android.gms.common.internal.GmsClientEventManager.onConnectionSuccess(Unknown Source:33)
at com.google.android.gms.common.api.internal.zaaw.zab(Unknown Source:292)
at com.google.android.gms.common.api.internal.zaak.zaaq(Unknown Source:125)
at com.google.android.gms.common.api.internal.zaak.onConnected(Unknown Source:105)
at com.google.android.gms.common.api.internal.zabe.onConnected(Unknown Source:101)
at com.google.android.gms.common.api.internal.zaq.onConnected(Unknown Source:6)
at com.google.android.gms.common.internal.zaf.onConnected(Unknown Source:2)
at com.google.android.gms.common.internal.BaseGmsClient$zzf.zzm(Unknown Source:24)
at com.google.android.gms.common.internal.BaseGmsClient$zza.zza(Unknown Source:12)
at com.google.android.gms.common.internal.BaseGmsClient$zzc.zzo(Unknown Source:11)
at com.google.android.gms.common.internal.BaseGmsClient$zzb.handleMessage(Unknown Source:49)
at android.os.Handler.dispatchMessage(Handler.java:107)
at com.google.android.gms.internal.common.zze.dispatchMessage(Unknown Source:8)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
I/Process: Sending signal. PID: 27425 SIG: 9
Heres My code :
#Override
public void onConnected(#Nullable Bundle bundle) {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
}
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
#SuppressLint("MissingPermission") Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double latit = location.getLatitude();
double longit = location.getLongitude();
LatLng kantor = new LatLng(-8.4603894,118.7560158);
LatLng User = new LatLng(latit,longit);
distance=SphericalUtil.computeDistanceBetween(User,kantor);
TextView jarak = findViewById(R.id.jarak);
jarak.setText("Jarak Dari Kantor :" + Math.round(distance) + " Meter");
Log.d(TAG,"Latitude" + String.valueOf(latit) +"Longitude" + String.valueOf(longit));
On Location Change works fine but this not i expected
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraPosition cameraPosition = new CameraPosition.Builder().target(new LatLng(latLng.latitude, latLng.longitude)).zoom(16).build();
latitude = location.getLatitude();
longitude = location.getLongitude();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
#SuppressLint("MissingPermission") Location location1 = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double latit = location.getLatitude();
double longit = location.getLongitude();
float[] results = new float[1];
Location.distanceBetween(latit,longit,-8.4604926,118.7560354,results);
float distance = results[0];
int meter = (int) (distance/10000);
TextView jarak = findViewById(R.id.jarak);
Android 10 introduced new permission called background location:
https://developer.android.com/training/location/permissions#background
For Android 10 devices or above, to get location while app is in background:
You need to declare Background Location permission in manifest.
Users must grant this permission in runtime.
(Update) Location services must be enabled on device.
(Update) Sample code:
Declare fine and background permission in AndroidManifest.xml (in manifest tag):
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
This is how you request these permissions from your Activity class (no permissions before Android 6):
// Android 10+
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION}, REQUEST_CODE);
// Android 6-9
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
This is how you check the result from your activity for Android 10+ devices (2 levels of permissions):
// Utility function
#RequiresApi(api = Build.VERSION_CODES.M)
public boolean isPermissionGranted(String permission) {
return checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
}
// Only fine location granted - no location if app is closed
isPermissionGranted(Manifest.permission.ACCESS_FINE_LOCATION) && !isPermissionGranted(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
// Fine & background location granted - location should (almost) always work:
isPermissionGranted(Manifest.permission.ACCESS_FINE_LOCATION) && isPermissionGranted(Manifest.permission.ACCESS_BACKGROUND_LOCATION)
For Android 6-9 devices you can just check for Manifest.permission.ACCESS_FINE_LOCATION
Related
am trying to create a Google Maps activity that gets the users current location and places a pin on the users' current location. I have tried the code with static latitude and longitude values and the map worked as it should. When I tried to get the LatLong values programmatically, the system threw a NullPointerException at line 127 containing the code double longitude = location.getLongitude();.
What am I doing wrong and how can I rectify it? Thanks in advance for your assistance.
Activity Code
#Override
public void onMapReady(GoogleMap googleMap) {
try {
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(getActivity(), new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 101);
}
} catch (Exception e){
e.printStackTrace();
}
LocationManager lm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
gmap = googleMap;
gmap.setMinZoomPreference(12);
gmap.setIndoorEnabled(true);
UiSettings uiSettings = gmap.getUiSettings();
uiSettings.setIndoorLevelPickerEnabled(true);
uiSettings.setMyLocationButtonEnabled(true);
uiSettings.setMapToolbarEnabled(true);
uiSettings.setCompassEnabled(true);
uiSettings.setZoomControlsEnabled(true);
LatLng ny = new LatLng(latitude, longitude);
gmap.moveCamera(CameraUpdateFactory.newLatLng(ny));
}
Logcat
Process: ke.co.mytech.mytech, PID: 8425
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLongitude()' on a null object reference
at ke.co.mytech.mytech.HomeFragment.onMapReady(HomeFragment.java:127)
at com.google.android.gms.maps.zzac.zza(Unknown Source)
at com.google.android.gms.maps.internal.zzaq.dispatchTransaction(Unknown Source)
at com.google.android.gms.internal.maps.zzb.onTransact(Unknown Source)
at android.os.Binder.transact(Binder.java:392)
at fg.b(:com.google.android.gms.dynamite_mapsdynamite#13280046#13.2.80 (040306-211705629):19)
at com.google.android.gms.maps.internal.bg.a(:com.google.android.gms.dynamite_mapsdynamite#13280046#13.2.80 (040306-211705629):5)
at com.google.maps.api.android.lib6.impl.be.run(:com.google.android.gms.dynamite_mapsdynamite#13280046#13.2.80 (040306-211705629):5)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5728)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
A few things that might help.
One, try using the FusedLocationProviderClient to get the location.
FusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(context);
fusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if(location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Log.i(TAG, "Latitude: " + latitude + " | Longitude: " + longitude);
} else {
Log.e(TAG, "Unable to retrieve location");
}
}
});
Second, I had this issue when I was testing on the emulator and it always raised the same exception as you are mentioning. What I did to fix it was to go into the Google Maps application on my emulator and let it pinpoint my location by clicking on the circle target button. I am not sure as to why it worked (I think it was because it saved my location which it was unable to do before).
Got the answer to what I was doing wrong in this question
I've just had some issues for odd reasons with the CameraUpdateFactory.
So I incorporated this code in an onclickListener on the GpsButton on a navigation fragment:
if (ContextCompat.checkSelfPermission(mapFragment.getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
Log.d("Permission checked", "checkSelfPermission passed with no errors");
map.setMyLocationEnabled(true);
Log.d("Permission checked", "Location Layer implementation successful");
} else {
//Request the Permission
ActivityCompat.requestPermissions(mapFragment.getActivity(), new String[]{
Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
This basically enables the location to be displayed as a blue dot on the map only when the GPS button is pressed. This has been perfectly functional so far.
I also incorporated a method to move the camera to my current location:
public void locateMe() {
LocationManager locationManager = (LocationManager) getActivity().getSystemService(LOCATION_SERVICE); // Getting LocationManager object from System Service LOCATION_SERVICE
Criteria criteria = new Criteria();// Creating a criteria object to retrieve provider
String provider = locationManager.getBestProvider(criteria, true);// Getting the name of the best provider
if (ContextCompat.checkSelfPermission(mapFragment.getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(mapFragment.getActivity(), new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 2);
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
double latitude = location.getLatitude(); //Getting latitude of the current location
double longitude = location.getLongitude(); // Getting longitude of the current location
myPosition = new LatLng(latitude, longitude); // Creating a LatLng object for the current location
map.moveCamera(CameraUpdateFactory.newLatLngZoom(myPosition, CAMPUS_DEFAULT_ZOOM_LEVEL));//Camera Update method
}
}
For some reason, this is hit or miss. 3 days ago, it was locking on a position that wasn't where I currently was located while for the past 2 days it worked perfectly. No code was changed whatsoever. Could someone please explain what's going on? Any fixes or suggestions would be appreciated.
This occurs because you are using getLastKnownLocation.
This can be done without starting the provider. Note that this location could be out-of-date, for example if the device was turned off and moved to another location.
If the provider is currently disabled, null is returned.
documentation
You have to use requestLocation updates if you want to retrieve the user's current documentation.
requestLocationUpdates documentation
I am looking for a solution to get the user's location in a specific time-interval in Android API 17 (Android 4.2) and when the phone is locked.
I've already tried some different code, checked a lot tutorials and searched almost everywhere on the web. The solution might be there, but I think it's a combination of lack of experience with Android developing and interpreting the different right solutions and approaches.
At first I had some pretty basic code, which worked very well when the screen was turned on. Even in the background, the location got updated (as I could check via a Toast message with the longitude and latitude).
I used a Handler to do so:
public void locationRunnable() {
final Handler locationHandler = new Handler();
final int distanceDelay = 5000; // milliseconds
locationHandler.postDelayed(new Runnable(){
public void run() {
// code
mMap.clear();
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;
}
mMap.setMyLocationEnabled(true);
mMap.setBuildingsEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
myLocation = locationManager.getLastKnownLocation(provider);
if (myLocation != null) {
latitudeCurrentPosition = myLocation.getLatitude();
longitudeCurrentPosition = myLocation.getLongitude();
}
currentPattern = shortTest;
Notification.Builder notificationBuilderChecking = new Notification.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.setContentTitle("Test app")
.setAutoCancel(true)
.setOnlyAlertOnce(false)
.setContentText("Getting location!")
.setPriority(Notification.PRIORITY_MAX)
.setLights(0xffffffff, 200, 200)
.setVibrate(currentPattern);
Notification notification2 = notificationBuilderChecking.build();
NotificationManager notificationMngr2 = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationMngr2.notify(NOTIFICATION_ID, notification2);
locationHandler.postDelayed(this, distanceDelay);
}
}, distanceDelay);
}
It's just a snippet and the purpose is that in the background, when the screen is locked, this will loop every 10 seconds. And it does. Even when the phone is locked, but only for about 3 times. After 3 times the timer goes up and the phone vibrates less frequent (Doze feature in the way?).
Also, the phone does vibrate, but the location isn't updated. When I unlock the phone with the app in the foreground, the location is still at the place when I locked the phone. After a while (10 seconds) it updates. I use a marker on the map to check.
Again: it works when the phone is unlocked.
Now I'm trying to use a Service, a Service (Intent Service), or a Broadcast Receiver, and start a new Thread, but I don't know how and nothing is working.
Some of the last code I have contains a not functioning Broadcast Receiver and the most recent code contains a AlarmManager:
public void getLocation(Context context) {
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmIntent.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
//After after 30 seconds
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis(), 10000, pi);
context.getSystemService(Context.CONNECTIVITY_SERVICE);
mMap.clear();
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
myLocation = locationManager.getLastKnownLocation(provider);
latitudeCurrentPosition = myLocation.getLatitude();
longitudeCurrentPosition = myLocation.getLongitude();
LatLng latLngCurrent = new LatLng(latitudeCurrentPosition, longitudeCurrentPosition);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLngCurrent));
mMap.animateCamera(CameraUpdateFactory.zoomTo(distZoom));
currentPattern = shortTest;
showNotification(context);
mHereIAm = mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitudeCurrentPosition, longitudeCurrentPosition))
.title(weAreHere)
.draggable(false)
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.marker_iconv3)));
mHereIAm.setTag(0);
mHereIAm.showInfoWindow();
}
AndroidManifest permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
But at the long of 10000, Android Studio is telling me "Value will be forced up to 60000 as of Android 5.1; don't rely on this to be exact..." etc. So an AlarmManager isn't useful either.
With the last code, my app isn't even running anymore.
But still: vibrations and stuff still occur, but location updates don't.
In short:
I need some basic (at least, I think it just can't be so difficult, as the only problem is that it's not working when the screen is locked) code, that updates my location on a certain, variable interval.
Maybe I have to use a Handler/Runnable, start a new Thread, use a Service or a Broadcast Receiver. Maybe an AlarmManager may work as well, but I don't know how and which to use.
This is my first post. If anything misses or you guys need more information, please ask. I'm trying to be as precise as possible, without using to much overhead.
Edit 01
Can I use a Job Service to do so? - I've updated the API to 21, so I can make use of this service, but I don't know if that's the right solution I'm looking for? Got some great tutorials for the use of it.
Edit 02
Let me be more clear with less overhead: I am looking for a solution to get the user's current location when the device is locked: with an API, a Service, an IntentService, a BroadcastReceiver, ... - every tutorial tells me something different, even here at Stack Overflow I have troubles with finding the right solution.
I was able to use a Service as well as an Intent Service, but I cannot request any location updates, because of some errors, like:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.name.name/com.name.name.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(boolean)' on a null object reference - searching for a solution for this error, gives me another error later on, and on, and on... I got myself stuck in an error-loop and a lot of unnecessary code.
I hope there is a simple way to get the user's location and you guys could help me. Thanks again.
Edit 03
I've followed the instructions on this tutorial and the location is checking. See the following code:
public class LocationService 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 LocationService(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(LocationService.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've disabled Network location and only allowed GPS location for testing - tested both.
And my MapsActivity:
public void getLocation(){
gps = new LocationService(MapsActivity.this);
if(gps.canGetLocation()) { // gps enabled} // return boolean true/false
latitudeCurrentPosition = gps.getLatitude(); // returns latitude
longitudeCurrentPosition = gps.getLongitude(); // returns longitude
latLngCurrent = new LatLng(latitudeCurrentPosition, longitudeCurrentPosition);
Toast toastLatCur = makeText(getApplicationContext(), "Lat Current: " + latitudeCurrentPosition + "" ,Toast.LENGTH_SHORT);
toastLatCur.show();
Toast toastLongCur = makeText(getApplicationContext(), "Long Current: " + longitudeCurrentPosition + "" ,Toast.LENGTH_SHORT);
toastLongCur.show();
}
else {
gps.showSettingsAlert();
}
if(goToLocation){
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLngCurrent));
goToLocation = false;
if(firstStart){
mMap.animateCamera(CameraUpdateFactory.zoomTo(distZoom));
firstStart = false;
}
}
vibrateNotification();
}
When the screen is locked, the phone vibrates as I told in vibrateNotificatoin() - works perfectly every 10 seconds. But the location doesn't get updated! So a Service is not the right way to solve this. Help!
You should use the service to perform tasks which are needed to be done even when the application is not running. Give a try.
I' m in a service, and I just need the latitude and longitude. Just two doubles. So, I did the following:
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
}
For some reason, the latitude and latitude are null. The documentation says this is possible if the information for location is unavailable, but it should be available, since I first check if the permissions are there in the if statement, right? In the phone that I am testing on, I do have location enabled. Why is the latitude and longitude null?
If you try this instead, what is the output?
locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
It's because, even if location is enabled, there is no "lastKnownLocation" available yet. If you go to (for example) google maps app and ask for current location, after location is successfully fetched, go to your app and it will work (lat and lon != null).
EDIT: I don't know the code for android location service API, but for google maps API is something like this (i'm sure is similar):
public void methodThatUseLocation() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), PERMISSIONS, MainActivity.REQUEST_LOCATION);
} else {
Location lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (lastLocation != null) {
Double latitude = lastLocation.getLatitude();
Double longitude = lastLocation.getLongitude();
// do something with latitude and longitude
} else {
requestLocationUpdate();
}
}
}
private void requestLocationUpdate() {
if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getActivity(), PERMISSIONS, MainActivity.REQUEST_LOCATION);
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}
}
The reason is, you are checking last known location, and if there were no locations previously fetched by this provider, all corresponding parameters will be null. Method getLastKnownLocation reuses information fetched by other apps/services, and it can happen that there were no information saved.
You can try to make single location update using method requestSingleUpdate, so you won't depend on your device state.
This question already has an answer here:
android requestLocationUpdates failing
(1 answer)
Closed 2 years ago.
Is there a way to obtain information without displaying the map?
I want get my coordinate of my place during the work with other activity.
tnx a lot.
By Using LocationManager you can get lat and lang :
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
The call to getLastKnownLocation() doesn't block - which means it will return null if no position is currently available - so you probably want to have a look at passing a LocationListener to the requestLocationUpdates() method instead, which will give you asynchronous updates of your location.
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
longitude = location.getLongitude();
latitude = location.getLatitude();
}
}
lm.requestLocationUpdates(LocationManager.GPS, 2000, 10, locationListener);
You'll need to give your application the ACCESS_FINE_LOCATION permission if you want to use GPS.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
You may also want to add the ACCESS_COARSE_LOCATION permission for when GPS isn't available and select your location provider with the getBestProvider() method.
Using this code able to get latitude and Longitude values and make
sure before using application you got permission from manifest for accessing location
if(isGPS) {
Geocoder gc = new Geocoder(getApplicationContext(), Locale.getDefault());
try
{
double lat=location.getLatitude();
double lng=location.getLongitude();
Toast.makeText(getApplicationContext(),lat+"and"+lng, Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
display("GPS not Enabled");
}
Manifest permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Use this if you want to get lat lon without internet
LocationManager lm = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
latitude = location.getLongitude();
longitude = location.getLatitude();