GPS location data does not match the location of AVD

Viewed 10

I write a simple code to show and update the latitude and longitude through GPS. The problem is they remain unchanged when I change the location of AVD.

public class PocketSphinxActivity extends Activity implements RecognitionListener {

boolean updateOn = false;
private static final int PERMISSIONS_FINE_LOCATION = 99;
TextView tv_lat, tv_lon, tv_add, tv_sen, tv_ud;
@SuppressLint("UseSwitchCompatOrMaterialCode")
Switch sw_locationupdates, sw_GPS;

LocationRequest locationRequest;
LocationCallback locationCallback;

FusedLocationProviderClient fusedLocationProviderClient;


/* Named searches allow to quickly reconfigure the decoder */

private static final String KWS_SEARCH = "wakeup";
private static final String STORE_SEARCH = "store";
private static final String LIBRARY_SEARCH = "library";
private static final String MUSEUM_SEARCH = "museum";
private static final String MENU_SEARCH = "menu";

/* Keyword we are looking for to activate menu */
private static final String KEYPHRASE = "guide me";

/* Used to handle permission request */
private static final int PERMISSIONS_REQUEST_RECORD_AUDIO = 1;

private SpeechRecognizer recognizer;
private TextToSpeech tts;
private HashMap<String, Integer> captions;

@SuppressLint("SetTextI18n")
@Override
public void onCreate(Bundle state) {
    super.onCreate(state);
    setContentView(R.layout.main);

    // Prepare the data for UI
    tv_lat = findViewById(R.id.tv_lat);
    tv_lon = findViewById(R.id.tv_lon);
    tv_add = findViewById(R.id.tv_add);
    sw_locationupdates = findViewById(R.id.sw_locationupdates);
    tv_sen = findViewById(R.id.tv_sen);
    sw_GPS = findViewById(R.id.sw_GPS);
    tv_ud = findViewById(R.id.tv_ud);

    captions = new HashMap<>();
    captions.put(KWS_SEARCH, R.string.kws_caption);
    captions.put(MENU_SEARCH, R.string.menu_caption);
    captions.put(LIBRARY_SEARCH, R.string.digits_caption);
    captions.put(MUSEUM_SEARCH, R.string.phone_caption);
    captions.put(STORE_SEARCH, R.string.forecast_caption);

    ((TextView) findViewById(R.id.caption_text))
            .setText("Preparing the recognizer");

    // set properties of LocationRequest
    locationRequest = LocationRequest.create();
    locationRequest.setInterval(1000 * 5);
    locationRequest.setFastestInterval(1000 * 1);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    // triggered whenever update interval is met
    locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(@NonNull LocationResult locationResult) {
            super.onLocationResult(locationResult);
            Location location = locationResult.getLastLocation();
            updateUI(location);
        }
    };


    sw_GPS.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (sw_GPS.isChecked()) {
                locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
                tv_sen.setText("Using Tower + Wifi");
            } else {
                locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                tv_sen.setText("Using GPS");
            }
        }
    });

    //StartLocUpdates();

    sw_locationupdates.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (sw_locationupdates.isChecked()) {
                //start tracking
                StartLocUpdates();

            } else {
                //stop tracking
                StopLocUpdates();
            }
        }
    });




    // Check if user has given permission to record audio
    int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.RECORD_AUDIO}, PERMISSIONS_REQUEST_RECORD_AUDIO);
        return;
    }

    // Recognizer initialization is a time-consuming and it involves IO,
    // so we execute it in async task

    new SetupTask(this).execute();
    updateGPS();

}

private void StopLocUpdates() {
    tv_lat.setText("Not tracking location");
    tv_lon.setText("Not tracking location");
    tv_add.setText("Not tracking location");
    tv_ud.setText("Location stop tracking");
    fusedLocationProviderClient.removeLocationUpdates(locationCallback);
}

private void StartLocUpdates() {
    //tv_ud.setText("stop ");
    tv_ud.setText("Location is being tracked");
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    fusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback,null);
    updateGPS();
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull  int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    //PERMISSIONS_REQUEST_RECORD_AUDIO
    if (requestCode == PERMISSIONS_FINE_LOCATION || requestCode == PERMISSIONS_REQUEST_RECORD_AUDIO) {

        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Recognizer initialization is a time-consuming and it involves IO,
            // so we execute it in async task
            updateGPS();
            new SetupTask(this).execute();
        } else {
            Toast.makeText(this, "This app permission to be granted in order to work properly", Toast.LENGTH_SHORT).show();
            finish();
        }
    }
}

private void updateGPS() {
    //get permission
    //get current location
    //update UI
    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(PocketSphinxActivity.this);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

        fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                //put values into UI
                updateUI(location);
            }
        });
    } else {
        //
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_FINE_LOCATION);
        }
    }
}

private void updateUI(Location location) {
    tv_lat.setText(String.valueOf(location.getLatitude()));
    tv_lon.setText(String.valueOf(location.getLongitude()));

    Geocoder geocoder = new Geocoder(PocketSphinxActivity.this);
    try{
        List<Address>addresses=geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
        tv_add.setText(addresses.get(0).getAddressLine(0));
    }
    catch(Exception e){
        tv_add.setText("Unable to get address");
    }
}

}

It seems that the location generated by fusedLocationProviderClient.getLastLocation() in method updateGPS() never changed. I wonder why.

private void updateGPS() {
    //get permission
    //get current location
    //update UI
    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(PocketSphinxActivity.this);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {

        fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                //put values into UI
                updateUI(location);
            }
        });
    } else {
        //
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_FINE_LOCATION);
        }
    }
0 Answers
Related