I'm making an app that tracks the user's location and ultimatly uploads it to a Firebase server.
I have created a simple app that displays the location when I press a button on screen. The problem is that it doesnt change the location when I press it again after I walked a few meters (I do get a new location when I re-enter the app though). What do I need to add in order for the app to update the location every X seconds? This is my activity:
package com.example.gpstest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermission();
client = LocationServices.getFusedLocationProviderClient(this);
Button button = findViewById(R.id.getLocation);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ActivityCompat.checkSelfPermission(MainActivity.this, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
return;
}
client.getLastLocation().addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if(location != null){
TextView lat = findViewById(R.id.location1);
TextView lon = findViewById(R.id.location2);
TextView alt = findViewById(R.id.location3);
lat.setText(Double.toString(location.getLatitude()));
lon.setText(Double.toString(location.getLongitude()));
alt.setText(Double.toString(location.getAltitude()));
}
}
});
}
});
}
private void requestPermission(){
ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 1);
}
}