What I want is to get just one fresh location and remove location updates after getting first location update and add it to realm but the problem am facing is getting more than 100 locations sometimes in a single update and executing 100 transactions in realm crash app
public void getCurrentLocation(final Context context) {
LocationRequest mLocationRequest;
final LocationCallback mLocationCallback;
final FusedLocationProviderClient mFusedLocationClient;
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(60000);
mLocationRequest.setFastestInterval(60000);
mLocationRequest.setNumUpdates(1);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult)
{
if (locationResult == null)
{
return;
}
mFusedLocationClient.removeLocationUpdates(this);
Location tempLocation = locationResult.getLastLocation();
if (locationResult.getLocations().size() > 0)
{
tempLocation = locationResult.getLocations().get(0);
}
if(tempLocation != null )
{
RealmManager.writeLocationInRealm(context, tempLocation, true, 0);
}
}
};
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);
}
You can achieve this via below code
This code is in Kotlin
private var fusedLocationClient: FusedLocationProviderClient?=null
in Your onCreate()
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this#YourActivity)
fusedLocationClient!!.lastLocation
.addOnSuccessListener { location: Location? ->
//Your lattitude location!!.latitude
//Your Longitude location.longitude
}
I faced the same problem and this is how I solve it in kotlin
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
locationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
super.onLocationResult(locationResult)
if (locationResult.lastLocation != null && locationResult.lastLocation.latitude > 0 && locationResult.lastLocation.longitude > 0) {
UserLocationObject.lastLocation = locationResult.lastLocation
fusedLocationClient.removeLocationUpdates(locationCallback)
}
}
}
Related
Iam trying to get current location updates for every 5 minutes and send to server but I am getting it in the foreground but I am not getting it on the background
I used Alarm Manager
I use this code :
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(60*1000);
mLocationRequest.setFastestInterval(10*1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (mLocationCallback == null)
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
if (location != null) {
if(BuildConfig.DEBUG)
mLastLocation = location;
}
}
}
};
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MasterApplica tion.getInstance().getApplicationContext());
fusedLocationProviderClient.requestLocationUpdates(mLocationR equest, mLocationCallback, Looper.getMainLooper());
The GoogleApiClient has been depreceted and now I am having some trouble learning the latest way to get constant location updates. Also, can I get the location updates using LocationCallback and LocationRequetMethod??
I am glad that I finally found it. The code is short. I have used LocationRequest and LocationCallback method. Also, I have used the fusedLocationProviderClient for requestLocationUpdates.
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient fusedLocationProviderClient;
TextView locationTextView;
LocationRequest locationRequest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationTextView = findViewById(R.id.location_text);
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
//Not the best practices to get runtime permissions, but still here I ask permissions.
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
}
//Instantiating the Location request and setting the priority and the interval I need to update the location.
locationRequest = locationRequest.create();
locationRequest.setInterval(100);
locationRequest.setFastestInterval(50);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
//instantiating the LocationCallBack
LocationCallback locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult != null) {
if (locationResult == null) {
return;
}
//Showing the latitude, longitude and accuracy on the home screen.
for (Location location : locationResult.getLocations()) {
locationTextView.setText(MessageFormat.format("Lat: {0} Long: {1} Accuracy: {2}", location.getLatitude(),
location.getLongitude(), location.getAccuracy()));
}
}
}
};
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
}
}
In activity_main.xml
<TextView
android:id="#+id/location_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/andika"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
Also, before all these, I have added this in my dependencies
implementation 'com.google.android.gms:play-services-location:17.0.0'
And this in my Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
And this keeps on updating in intervals you choose
Hi so continious location update is something you should avoid as it drains battery. You can use locationlistner where you could listen to location change. Say you want to update the location and get the attitude and longitude on every 10 meter change.
Sample code to check last,long every 100 meter
class LocationService : Service(), LocationListener {
protected var locationManager: LocationManager? = null
var checkGPS = false
var checkNetwork = false
// boolean canGetLocation = false;
var loc: Location? = null
// double latitude;
// double longitude;
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onLocationChanged(location: Location) {
// Toast.makeText(getApplicationContext(), Double.toString(location.getLatitude()) + location.getLongitude(), Toast.LENGTH_LONG).show();
}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
override fun onProviderEnabled(provider: String) {}
override fun onProviderDisabled(provider: String) {}
override fun onCreate() {
super.onCreate()
location
}
Toast.makeText(getApplicationContext(), Double.toString(latitude) + longitude + "from method", Toast.LENGTH_LONG).show();
private val location: Location?
private get() {
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
)
!= PackageManager.PERMISSION_GRANTED
) {
}
locationManager = applicationContext
.getSystemService(LOCATION_SERVICE) as LocationManager
checkGPS = locationManager!!
.isProviderEnabled(LocationManager.GPS_PROVIDER)
checkNetwork = locationManager!!
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
locationManager!!.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES.toFloat(), this
)
if (locationManager != null) {
val fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
fusedLocationClient.lastLocation.addOnSuccessListener { location ->
if (location != null) {
Toast.makeText(
applicationContext,
java.lang.Double.toString(location.latitude) + location.longitude + "from method",
Toast.LENGTH_LONG
).show()
}
}
}
Toast.makeText(getApplicationContext(), Double.toString(latitude) + longitude + "from method", Toast.LENGTH_LONG).show();
return loc
}
companion object {
private const val MIN_DISTANCE_CHANGE_FOR_UPDATES: Long = 100
private const val MIN_TIME_BW_UPDATES: Long = 30
}
}
I am using FusedLocationProviderClient to trace location and I want to get the best location by using getAccuracy() method. I checked this method on some devices and it returns 1500 and sometimes 1700 while it has to be less than a few meters(less than 12). Why is this happening and what should I do?
Thanks in Advance.
My code:
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
Location location = locationResult.getLastLocation();
float acc = location.getAccuracy();
if (location != null && location.getAccuracy() < 10){
if(preLocation == null){
preLocation = location;
locationChanged(location);
sendLocation(location.getLatitude(), location.getLongitude());
}else if (preLocation.getLatitude() != location.getLatitude() && preLocation.getLongitude() != location.getLongitude()) {
// Logic to handle location object
locationChanged(location);
preLocation = location;
}
}
}
};
Try to set locationRequest priority to High Accuracy like this
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
} else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
}
}
LocationCallback mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
//Do what you want with the location here
}
}
};
I am using a simple code and keep getting
java.lang.NullPointerException: Listener must not be null
I am only using a very short and simple code to try and get my current location, yet I can't get it to work. It might has to do something with that "null" at the looper place in the requestLocationUpdates callback. But I am not sure.
I've been trying all day already.
Here is the short code:
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient mFusedLocationClient;
private LocationCallback mLocationCallback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
LocationRequest mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
//
} else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback,
null /* Looper */);
}
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
// Update UI with location data
TextView tv = (TextView) findViewById(R.id.tv);
Double latDouble = location.getLatitude();
String latString = latDouble.toString();
tv.setText(latString);
}
};
};
}
All I want is to simply get current location, why is it giving me such hard times? What causes this error?
thanks
You're trying to use mLocationCallback before you initialise it. Just move this code :
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
// Update UI with location data
TextView tv = (TextView) findViewById(R.id.tv);
Double latDouble = location.getLatitude();
String latString = latDouble.toString();
tv.setText(latString);
}
};
};
before this:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
//
} else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback,
null /* Looper */);
}
The null in the Looper thread has nothing to do with it. By passing it as null you keep your callbacks on the calling thread.
My FusedLocationProviderClient is not stopping after I call
fusedLocationClient.removeLocationUpdates(locationCallback);
The GPS location icon shows indefinitely in the notification bar until I manually terminate the service.
I am calling stopLocationUpdates in the onDestroy() method as well.
To start it, I am calling:
fusedLocationClient.requestLocatonUpdates(locationRequest, locationCallback, null);
locationCallback being:
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Location lastLocation = null;
for (Location location : locationResult.getLocations()) {
if (lastLocation != null) {
if (location.getTime() < lastLocation.getTime()) {
lastLocation = location;
}
} else {
lastLocation = location;
}
}
if (lastLocation != null) {
String msg1 = "Best location: http://www.google.com/maps/search/?api=1&query=" + lastLocation.getLatitude() + "%2C" + lastLocation.getLongitude();
sendSms(lastReceivedNumber, msg1);
}
stopLocationUpdates();
}
};
Here is stopLocationUpdates():
private void stopLocationUpdates() {
if (fusedLocationClient != null) {
fusedLocationClient.removeLocationUpdates(locationCallback);
}
fusedLocationClient = null;
}
I can't understand why it doesn't stop.
Any help appreciated.
Here is what I did:
private void startLocationUpdates() {
fusedLocationClient = new FusedLocationProviderClient(this);
locationRequest = new LocationRequest().setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
Location lastLocation = null;
for (Location location : locationResult.getLocations()) {
if (lastLocation != null) {
if (location.getTime() < lastLocation.getTime()) {
lastLocation = location;
}
} else {
lastLocation = location;
}
}
if (lastLocation != null) {
String msg1 = "Best location: http://www.google.com/maps/search/?api=1&query=" + lastLocation.getLatitude() + "%2C" + lastLocation.getLongitude();
sendSms(lastReceivedNumber, msg1);
}
stopLocationUpdates();
}
};
try {
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null);
} catch (SecurityException e) {
e.printStackTrace();
}
}
private void stopLocationUpdates() {
if (fusedLocationClient != null) {
fusedLocationClient.removeLocationUpdates(locationCallback);
}
fusedLocationClient = null;
locationRequest = null;
locationCallback = null;
}
I was only nulling the client, nulling everything seems to solve the issue.
Now all i have to do is call startLocationUpdates() and it takes care of itself, destroying everything afterwards.