Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

How to save location data in array in service and send that array to activity/fragment? [Android/Java]

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a LocalBroadcastManager to pass the data via bundle in Intent from Service

public void onLocationResult(LocationResult locationResult) {
     super.onLocationResult(locationResult);
     Log.d("LOCALIZATOR_LOG", "Lat: " + locationResult.getLastLocation().getLatitude() + ", Lng: " + locationResult.getLastLocation().getLongitude());
     Intent intent = new Intent("LatLongUpdate");
     intent.putExtra("Latitude", locationResult.getLastLocation().getLatitude());
     intent.putExtra("Longitude", locationResult.getLastLocation().getLongitude());
     LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

And then in Activity

private ArrayList<ArrayList<Long>> locations = new ArrayList<>();
private BroadcastReceiver locationReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Long latitude = intent.getLongExtra("Latitude");
        Long longitude = intent.getLongExtra("Longitude");
        //save to array in activity
        ArrayList<Long> loc = new ArrayList<>();
        loc.add(latitude);
        loc.add(longitude);
        locations.add(loc)
    }
};
LocalBroadcastManager.getInstance(this).registerReceiver(
            locationReceiver, new IntentFilter("LatLongUpdate"));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...