I'm creating an Android program with Java and I need to get location every 5s (and I already did it using LocationServices and FusedLocationProviderClient). Everything works fine -> I mean logs are created and location is updating. Now I need to save that data (instead of showing it in logger) to an array like this:
PSEUDOCODE:
array[0][0] = lat1,
array[0][1] = lng1,
array[1][0] = lat2,
array[1][1] = lng2 ... etc...
and send that array to an Activity/Fragment where I started service. How to do it? I want to pass the data continuously or after service ends. Help me please
I have created LocationService which is implementing Service like this:
@Override
public void onCreate() {
super.onCreate();
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
locationCallback = new LocationCallback(){
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
Log.d("LOCALIZATOR_LOG", "Lat: " + locationResult.getLastLocation().getLatitude() + ", Lng: " + locationResult.getLastLocation().getLongitude());
}
};
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
requestLocation();
return super.onStartCommand(intent, flags, startId);
}
private void requestLocation() {
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}
and in my Activity I use that service like this:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
if(Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
startLocService();
}
} else {
startLocService();
}
}
void startLocService() {
Intent intent = new Intent(TestActivity.this, LocationService.class);
startService(intent);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case 1:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED){
} else {
Toast.makeText(this, "I need a permission", Toast.LENGTH_LONG).show();
}
}
}
question from:
https://stackoverflow.com/questions/65880399/how-to-save-location-data-in-array-in-service-and-send-that-array-to-activity-fr 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…