Geotag and Geofence Changes

This commit is contained in:
ravik
2025-08-06 15:04:27 +05:30
parent a263278382
commit 1af132ab36
53 changed files with 5545 additions and 98 deletions
@@ -12,7 +12,6 @@ import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
@@ -20,6 +19,7 @@ import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
@@ -37,6 +37,7 @@ import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
@@ -95,6 +96,8 @@ import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import android.content.SharedPreferences;
public class StoreImageActivity extends AppCompatActivity implements View.OnClickListener {
private static final int PERMISSION_ALL = 99;
private Button btn_save;
@@ -102,6 +105,7 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
private String _pathforcheck, _path, str, img_str, selfie_imge, visit_date, username, counter_id, userType;
private Lorealba_Database db;
private Runnable run;
private boolean isGeoTagAlertShown = false;
private Toolbar toolbar;
private ProgressDialog loading;
private Retrofit adapter;
@@ -114,6 +118,7 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
private LocationCallback locationCallback = null;
private SharedPreferences.Editor editor = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@@ -205,7 +210,6 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.img_cam_selfie) {
clickFlag = true;
_pathforcheck = counter_id + "_Counter_Selfie_img_" + username + "_" + visit_date.replace("/", "") + "_" + getCurrentTime().replace(":", "") + ".jpg";
@@ -330,11 +334,9 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
StoreImageActivity.this.finish();
}
}
return super.onOptionsItemSelected(item);
}
private void AttempBaCoverage(final ProgressDialog loading, Context context) {
try {
getMid();
@@ -546,7 +548,6 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
} else {
/// checking GeoFencing
getLastLocation();
checkingGeoFencing(getMid());
}
}
@@ -558,7 +559,6 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
}
if (!success_geoTag) {
getLastLocation();
checkingGeoFencing(getMid());
}
checkgpsEnableDevice();
getMid();
@@ -579,28 +579,63 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
}
private void enableLocationSettings() {
LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, // priority
5000 // intervalMillis: 5 seconds
).setMinUpdateIntervalMillis(3000) // fastest interval
LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 5000)
.setMinUpdateIntervalMillis(3000)
.setMaxUpdateDelayMillis(6000)
.setMinUpdateDistanceMeters(0f)// Optional batching
.setWaitForAccurateLocation(true) // Optional, improves first fix
.build();
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest).setAlwaysShow(true); // show dialog if GPS is off
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
.addLocationRequest(locationRequest)
.setAlwaysShow(true); // Show dialog if GPS is off
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
settingsClient.checkLocationSettings(builder.build()).addOnSuccessListener(locationSettingsResponse -> {
// All location settings are satisfied. You can request location updates here.
}).addOnFailureListener(e -> {
if (e instanceof ResolvableApiException) {
try {
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult((Activity) this, REQUEST_LOCATION);
} catch (IntentSender.SendIntentException sendEx) {
// Ignore the error.
sendEx.fillInStackTrace();
settingsClient.checkLocationSettings(builder.build())
.addOnSuccessListener(locationSettingsResponse -> {
// All location settings are satisfied, start updates
startLocationUpdates(locationRequest);
})
.addOnFailureListener(e -> {
if (e instanceof ResolvableApiException) {
try {
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult((Activity) this, REQUEST_LOCATION);
} catch (IntentSender.SendIntentException sendEx) {
sendEx.printStackTrace();
}
}
});
}
private void startLocationUpdates(LocationRequest locationRequest) {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(@NonNull LocationResult locationResult) {
if (locationResult == null) return;
for (Location location : locationResult.getLocations()) {
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
}
}
}
});
};
// Don't forget permissions check
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Request permissions if not granted
return;
}
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
}
private boolean hasGPSDevice(Context context) {
final LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (mgr == null) return false;
@@ -643,7 +678,6 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
if (jcpObject != null && db.insertJCPData(jcpObject)) {
/// checking GeoFencing
getLastLocation();
checkingGeoFencing(getMid());
AlertandMessages.showToastMsg(context, "Journey Plan Download Successfully.");
JourneyPlan jcp = db.getBIDfromJCP(username, counter_id);
if (jcp != null && jcp.getCheckout() != null && !jcp.getCheckout().isEmpty() && jcp.getCheckout().equals("Y")) {
@@ -829,8 +863,36 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
if (fusedLocationClient == null) {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
// fastest interval
LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 5000).setMinUpdateIntervalMillis(3000) // fastest interval
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Request permissions if not granted
checkAndRequestPermissions();
return;
}
// First, try to get the last known location
fusedLocationClient.getLastLocation()
.addOnSuccessListener(location -> {
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
checkingGeoFencing(getMid());
} else {
// No last known location, request updates for a new one
requestNewLocation();
}
})
.addOnFailureListener(e -> {
// Fallback: explicit request for a new location
requestNewLocation();
});
}
private void requestNewLocation() {
LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 5000)
.setMinUpdateIntervalMillis(3000)
.setMaxUpdateDelayMillis(6000)
.setMinUpdateDistanceMeters(0f)
.setWaitForAccurateLocation(true)
.build();
locationCallback = new LocationCallback() {
@Override
@@ -839,7 +901,10 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
Log.d("Location", "Lat: " + lat + ", Lng: " + lon);
Log.d("Location", "Lat: " + lat + ", Lng: " + lon + " (new)");
checkingGeoFencing(getMid());
stopLocationUpdates(); // Stop updates after first valid location
break;
}
}
}
@@ -847,6 +912,7 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// Request permissions if not granted
checkAndRequestPermissions();
return;
}
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
@@ -861,27 +927,37 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
@Override
public void onDestroy() {
super.onDestroy();
stopLocationUpdates();
// stopLocationUpdates();
if (loading != null && loading.isShowing()) {
loading.dismiss();
}
}
@Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
private void checkingGeoFencing(JourneyPlan jcp) {
if (jcp != null && jcp.getBID() != null) {
if (jcp.getGeoTag() != null && !jcp.getGeoTag().equalsIgnoreCase(CommonString.KEY_N) && jcp.getGeoFencingAllow() != null && jcp.getGeoFencingAllow() == 1) {
int distance = jcp.getGeoFencingRadius() != null ? jcp.getGeoFencingRadius() : 0;
int current_dist_from_store_using_lat = 0;
Log.d("latdata",lat + ","+lon + ","+jcp.getLatitude() + ","+jcp.getLongitude());
if (jcp.getLatitude() != 0.0 && jcp.getLongitude() != 0.0 && jcp.getGeoFencingRadius() != 0 && lat != 0.0 && lon != 0.0) {
current_dist_from_store_using_lat = DistanceUtils.calculateDistanceInMeters(lat, lon, jcp.getLatitude(), jcp.getLongitude());
Log.d("TagLoc", "Radius " + distance + "\nCurrent dist " + current_dist_from_store_using_lat);
if (current_dist_from_store_using_lat > distance) {
String msg = getString(R.string.you_need_to_be_within) + " " + distance + " metres " + getString(R.string.you_need_to_be_in_the_store) +
"\n\n" + getString(R.string.distance_from_the_store) + " " + current_dist_from_store_using_lat + " " + getString(R.string.meters);
if (isFinishing() || (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed())) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getResources().getString(R.string.alert));
builder.setMessage(msg).setCancelable(false).setPositiveButton(getResources().getString(R.string.ok), (dialog1, id) -> {
dialog1.cancel();
dialog1.dismiss();
finishAffinity();
});
AlertDialog alert = builder.create();
@@ -889,18 +965,30 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
}
}
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getResources().getString(R.string.dialog_title));
builder.setMessage(getString(R.string.first_geotag_the_store)).setCancelable(false).setPositiveButton(getResources().getString(R.string.ok), (dialog1, id) -> {
dialog1.cancel();
success_geoTag = false;
Intent in = new Intent(this, GeoTaggingActivity.class);
startActivity(in);
});
AlertDialog alert = builder.create();
alert.show();
if (isFinishing() || (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed())) {
return;
}
db.open();
if (!isGeoTagAlertShown && db.getinsertGeotaggingData(storeId.toString(), counter_id, username, "Y").isEmpty()) {
isGeoTagAlertShown = true;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getResources().getString(R.string.dialog_title));
builder.setMessage(getString(R.string.first_geotag_the_store))
.setCancelable(false)
.setPositiveButton(getResources().getString(R.string.ok), (dialog1, id) -> {
dialog1.dismiss();
success_geoTag = false;
isGeoTagAlertShown = false; // Reset the flag if needed for future
Intent in = new Intent(this, GeoTaggingActivity.class);
startActivity(in);
// Optionally start geo tagging activity here
});
AlertDialog alert = builder.create();
alert.show();
}
}
}
}
}
@@ -122,7 +122,7 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
AlertandMessages.showToastMsg(view.getContext(), getResources().getString(R.string.takeimage));
}
} catch (Exception e) {
e.fillInStackTrace();
e.printStackTrace();
}
});
camera_fab.setOnClickListener(view -> {
@@ -141,13 +141,14 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
AlertandMessages.showToastMsg(context, getResources().getString(R.string.nonetwork));
}
} catch (Exception e) {
e.fillInStackTrace();
e.printStackTrace();
}
});
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
}, LOCATION_PERMISSION_REQUEST_CODE);
}
locationCallback = new LocationCallback() {
@Override
@@ -167,7 +168,6 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
if (distance > 10) {
previousLatitude = latitude;
previousLongitude = longitude;
updateMapWithLocation(latitude, longitude);
}
}
@@ -178,13 +178,27 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
}
private void startLocationUpdates() {
@SuppressLint("VisibleForTests") LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 5000)
.setMinUpdateIntervalMillis(1000)
LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 5000)
.setMinUpdateIntervalMillis(3000)
.setWaitForAccurateLocation(true)
.setMaxUpdateDelayMillis(6000)
.build();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
fusedLocationClient.getLastLocation().addOnSuccessListener(this, location -> {
if (location != null && (latitude == 0.0 && longitude == 0.0)) {
latitude = location.getLatitude();
longitude = location.getLongitude();
previousLatitude = latitude;
previousLongitude = longitude;
updateMapWithLocation(latitude, longitude);
}
});
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1001);
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
}
}
@@ -193,7 +207,6 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
Log.e("jeevanp", "" + lat);
String address = "";
try {
List<Address> addressList = geocoder.getFromLocation(lat, lon, 1);
if (addressList != null && !addressList.isEmpty()) {
address = addressList.get(0).getAddressLine(0);
@@ -236,31 +249,51 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(22.5726, 88.3639), 15));
// Enable My Location layer
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude,longitude), 15));
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true); // ✅ this shows blue dot
mMap.getUiSettings().setMyLocationButtonEnabled(true); // ✅ this shows the GPS icon
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
startLocationUpdates();
} else {
// request permission
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
}
fusedLocationClient.getLastLocation().addOnSuccessListener(location -> {
if (location != null && (latitude == 0.0 && longitude == 0.0)) {
latitude = location.getLatitude();
longitude = location.getLongitude();
previousLatitude = latitude;
previousLongitude = longitude;
updateMapWithLocation(latitude, longitude);
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
boolean locationGranted = false;
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
locationGranted = true;
break;
}
}
if (locationGranted) {
if (mMap != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
}
startLocationUpdates();
} else {
Toast.makeText(this, "Location permissions are required for geotagging", Toast.LENGTH_LONG).show();
}
}
}
@@ -327,9 +360,6 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
if (mapFragment != null) {
mapFragment.getMapAsync(this);
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
app_ver = String.valueOf(getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
} catch (PackageManager.NameNotFoundException ignored) {
@@ -363,14 +393,12 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
@Override
protected String doInBackground(Void... params) {
try {
// uploading Geotag
uploadflag = false;
geotaglist = db.getinsertGeotaggingData(jcpGetset.getStoreId().toString(), counter_id, username, CommonString.KEY_N);
if (!geotaglist.isEmpty()) {
String jsonString2 = getString();
Log.e("jsonString2", jsonString2);
// Log.e("jsonString2", jsonString2);
String result = upload.downloadDataUniversal(jsonString2);
Log.e("jsonString2", result);
// Log.e("jsonString2", result);
if (result.equalsIgnoreCase(CommonString.MESSAGE_NO_RESPONSE_SERVER)) {
uploadflag = false;
throw new SocketTimeoutException();
@@ -469,11 +497,10 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
}
private void enableLocationSettings() {
LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, // priority
5000 // intervalMillis: 5 seconds
).setMinUpdateIntervalMillis(3000) // fastest interval
LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 5000)
.setMinUpdateIntervalMillis(3000)
.build();
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest).setAlwaysShow(true); // show dialog if GPS is off
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest).setAlwaysShow(true);
SettingsClient settingsClient = LocationServices.getSettingsClient(this);
settingsClient.checkLocationSettings(builder.build()).addOnSuccessListener(locationSettingsResponse -> {