I made an app that stores the position of the device (latitude and longitude) and to actually test it I tried to change the GPS location of the emulator from the default location in Mountain View to a random location in Rome. I followed this thread to do it. The problem is that my app still stores the default location rather than the new location I set.
This is how I access the location:
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 m
private static final long MIN_TIME_BW_UPDATES = 1000 * 60; // 1 minute
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
Location location = null;
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
throw new Exception("GPS must be turned on!");
}
else {
if (isNetworkEnabled) {
if (ActivityCompat.checkSelfPermission((Activity)mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission((Activity)mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
throw new Exception("Permission needed for location!");
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
return location;
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS turned off");
alertDialog.setMessage("Turn on the GPS!");
alertDialog.setPositiveButton("Impostazioni", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
}
This is how I use those methods and actually store the location on the Database:
public class HomeActivity extends AppCompatActivity {
private GPSTracker gpsTracker;
String ServerURL = "http://10.0.2.2/api/insert.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
final Button bottone1 = findViewById(R.id.bottone1);
bottone1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(HomeActivity.this, MainActivity.class);
gpsTracker = new GPSTracker(HomeActivity.this);
Location location = gpsTracker.getLocation();
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
DateFormat format = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date datenotformatted = new Date(location.getTime());
String date = format.format(datenotformatted);
String lat = String.valueOf(latitude);
String lon = String.valueOf(longitude);
startActivity(intent);
insertData(lat, lon, date);
}
else {
gpsTracker.showSettingsAlert();
}
}
});
}
private void insertData(final String latitude, final String longitude, final String date){
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String first = latitude;
String second = longitude;
String third = date;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(ServerURL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("latitudine", first));
nameValuePairs.add(new BasicNameValuePair("longitudine", second));
nameValuePairs.add(new BasicNameValuePair("data", third));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity == null) {
Toast.makeText(HomeActivity.this, "Errore.", Toast.LENGTH_LONG).show();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "Success.";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(latitude, longitude, date);
}