I have a gpsTracker java class which contains the onLocationChanged() method. I want to link my MainActivity's OnCreate function with this onLocationChanged() method.
public void onLocationChanged(Location newlocation) {
Log.d("latitude", "old" + Double.toString(this.location.getLatitude()));
Log.d("Longitude", "old " +
Double.toString(this.location.getLatitude()));
Log.i("info","LOCATION CHANGED");
Log.d("latitude", "NEW: CHANGED TO KOLKATA" +
Double.toString(newlocation.getLatitude()));
Log.d("Longitude", "NEW: CHANGED TO KOLKATA " +
Double.toString(newlocation.getLatitude()));
this.location = newlocation;
JSONObject locationChange = new JSONObject();
getLocationName(location.getLatitude(), location.getLongitude());
try {
locationChange.put("userid",
PreferenceManager.getInstance().getUserId());
locationChange.put("location", addressString);
locationChange.put("connection",
PreferenceManager.getInstance().getConnectAllow() ? "1" : "0");
locationChange.put("connection", "0");
locationChange.put("notification",
PreferenceManager.getInstance().getPushNotiAllow() ? "0" : "1");
Log.d(TAG, "LOCATION CHANGED BY GPS FUNCTION: " + locationChange);
RequestHandler.getInstance().postWithHeader(null,
getString(R.string.baseurl) + getString(R.string.settings),
locationChange, this,
AppConstants.ApiRequestCodeKey.SAVE_APP_SETTINGS);
}catch (JSONException e) {
e.printStackTrace();
}
}
public void getLocationName(double latitude, double longitude) {
Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
addressString = addresses.get(0).getAddressLine(0)
+ addresses.get(0).getAddressLine(1) + " ";
} catch (IOException e) {
e.printStackTrace();
}
}>
The onCreate function in the MainActivity() contains this.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_frame);
utils.mixpanelTrack(this, "Reached Home Page");
homeFragObj = this;
initViews();
initSetup();
initListeners();
loadData();
>
To receive every location change in your Activiy, it´s the best option to use
Broadcasts
. Create a instance variable ofBroadcastReceiver
:In
onCreate()
add this receiver:Don´t forget to unregister the receiver if Activity closes:
And on
OnLocationChange
in yourUtils
class, send theBroadcast
after you have the coordinates like this:What you need is the
context
that you can pass via your constructor of yourUtils
class, for example, if you create an instance in yourActivity
:This is just a basic answer, there are some things you have to be aware of.