geofence update code

This commit is contained in:
2026-03-28 18:11:58 +05:30
parent 5801aa3e6f
commit f1bdf73db2
40 changed files with 974 additions and 610 deletions
+2 -2
View File
@@ -12,8 +12,8 @@ android {
applicationId "com.cpm.lorealbaMabeline"
//noinspection OldTargetApi
targetSdk 34
versionCode 24
versionName "3.2"
versionCode 23
versionName "3.1"
multiDexEnabled true
useLibrary 'org.apache.http.legacy'
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
+2 -2
View File
@@ -11,8 +11,8 @@
"type": "SINGLE",
"filters": [],
"attributes": [],
"versionCode": 24,
"versionName": "3.2",
"versionCode": 23,
"versionName": "3.1",
"outputFile": "app-release.apk"
}
],
@@ -307,7 +307,7 @@ public class CounterLoginActivity extends AppCompatActivity implements View.OnCl
JSONObject jsonObject = new JSONObject();
jsonObject.put("Latitude", lat);
jsonObject.put("Longitude", lon);
jsonObject.put("Appversion", app_ver);
jsonObject.put("Appversion", app_ver +"T1");
jsonObject.put("Attmode", "0");
jsonObject.put("Networkstatus", "0");
jsonObject.put("Manufacturer", manufacturer);
@@ -502,7 +502,7 @@ public class CounterLoginActivity extends AppCompatActivity implements View.OnCl
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0);
String version = pInfo.versionName;
versioncode_txt.setText("Version : " + version);
versioncode_txt.setText("Version : " + version +"-T1");
} catch (PackageManager.NameNotFoundException e) {
e.fillInStackTrace();
versioncode_txt.setText("Version : 0.0");
@@ -818,7 +818,7 @@ public class DealarBoardActivity extends AppCompatActivity implements Navigation
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0);
String version = pInfo.versionName;
version_code.setText("Version : " + version);
version_code.setText("Version : " + version +"-T1");
} catch (PackageManager.NameNotFoundException e) {
e.fillInStackTrace();
version_code.setText("Version : 0.0");
@@ -166,7 +166,7 @@ public class IMEILoginActivity extends AppCompatActivity implements GoogleApiCli
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0);
String version = pInfo.versionName;
versioncode_txt.setText("Version : " + version);
versioncode_txt.setText("Version : " + version+"-T1");
} catch (PackageManager.NameNotFoundException e) {
e.fillInStackTrace();
versioncode_txt.setText("Version : 0.0");
@@ -0,0 +1,119 @@
package com.cpm.lorealbaMabeline;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.Priority;
public class LocationEngine {
public interface LocationResultListener {
void onLocationReady(Location location, float accuracy);
void onFailure(String msg);
}
private final Context context;
private final FusedLocationProviderClient fusedClient;
private LocationCallback locationCallback;
private Location bestLocation = null;
private float bestAccuracy = Float.MAX_VALUE;
private Handler handler = new Handler(Looper.getMainLooper());
public LocationEngine(Context context) {
this.context = context;
fusedClient = LocationServices.getFusedLocationProviderClient(context);
}
public void start(LocationResultListener listener) {
com.google.android.gms.location.LocationRequest request = new com.google.android.gms.location.LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 2000L)
.setMinUpdateIntervalMillis(1000L)
.setMaxUpdateDelayMillis(3000L)
.setWaitForAccurateLocation(true) // Optional, improves first fix
.build();
/* LocationRequest request = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 2000L) // 👈 IMPORTANT
.setMinUpdateIntervalMillis(1000L)
.setMaxUpdateDelayMillis(3000L)
.setWaitForAccurateLocation(true)
.build();*/
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(@NonNull LocationResult result) {
for (Location location : result.getLocations()) {
if (location == null) continue;
float accuracy = location.getAccuracy();
// 🔥 Track best location always
if (accuracy < bestAccuracy) {
bestAccuracy = accuracy;
bestLocation = location;
}
Log.d("LocationEngine",
"Lat: " + location.getLatitude()
+ " Lng: " + location.getLongitude()
+ " Acc: " + accuracy);
// ✅ Accept good or stable location
if (accuracy <= 80) {
stop();
listener.onLocationReady(location, accuracy);
return;
}
}
}
};
if (ActivityCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
listener.onFailure("Permission not granted");
return;
}
fusedClient.requestLocationUpdates(request, locationCallback, Looper.getMainLooper());
// ⏱ Timeout fallback (VERY IMPORTANT)
handler.postDelayed(() -> {
if (bestLocation != null) {
Log.d("LocationEngine", "Using fallback location");
listener.onLocationReady(bestLocation, bestAccuracy);
} else {
listener.onFailure("Unable to fetch location");
}
stop();
}, 8000);
}
public void stop() {
if (locationCallback != null) {
fusedClient.removeLocationUpdates(locationCallback);
}
handler.removeCallbacksAndMessages(null);
}
}
@@ -283,7 +283,7 @@ public class UserLoginActivity extends AppCompatActivity implements View.OnClick
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0);
String version = pInfo.versionName;
versioncode_txt.setText("Version : " + version);
versioncode_txt.setText("Version : " + version +"-T1");
} catch (PackageManager.NameNotFoundException e) {
e.fillInStackTrace();
versioncode_txt.setText("Version : 0.0");
@@ -11,7 +11,6 @@ import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
@@ -27,7 +26,6 @@ import androidx.core.content.ContextCompat;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.Looper;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
@@ -35,20 +33,16 @@ import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.common.api.ResolvableApiException;
import com.cpm.lorealbaMabeline.Database.Lorealba_Database;
import com.cpm.lorealbaMabeline.LocationEngine;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.Priority;
import com.google.android.gms.location.SettingsClient;
import com.google.gson.Gson;
import com.cpm.lorealbaMabeline.BuildConfig;
import com.cpm.lorealbaMabeline.Database.Lorealba_Database;
import com.cpm.lorealbaMabeline.DealarBoardActivity;
import com.cpm.lorealbaMabeline.R;
import com.cpm.lorealbaMabeline.constant.AlertandMessages;
@@ -103,6 +97,7 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
private ImageView img_cam, img_clicked;
private String _pathforcheck, _path, str, img_str, selfie_imge, visit_date, username, counter_id, userType;
private Lorealba_Database db;
private LocationEngine locationEngine;
private Runnable run;
private boolean isGeoTagAlertShown = false;
private Toolbar toolbar;
@@ -116,12 +111,14 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
private FusedLocationProviderClient fusedLocationClient = null;
private LocationCallback locationCallback = null;
private SharedPreferences.Editor editor = null;
private boolean isLocationFetching = false;
private ProgressBar locationLoader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_store_image);
locationEngine = new LocationEngine(this);
db = new Lorealba_Database(this);
db.open();
SharedPreferences preferences = PrefHelper.getPrefs(this);
@@ -130,6 +127,13 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
img_cam = (ImageView) findViewById(R.id.img_selfie);
img_clicked = (ImageView) findViewById(R.id.img_cam_selfie);
locationLoader = findViewById(R.id.locationLoader);
locationLoader.setVisibility(View.VISIBLE);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
);
btn_save = (Button) findViewById(R.id.btn_save_selfie);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
@@ -169,9 +173,8 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
} catch (Exception e) {
e.fillInStackTrace();
}
checkAndRequestPermissions();
getLastLocation();
fetchLocationAndCheckGeoFence();
}
private void checkdates() {
@@ -546,7 +549,7 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
}
} else {
/// checking GeoFencing
getLastLocation();
fetchLocationAndCheckGeoFence();
}
}
@@ -557,13 +560,13 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
success_geoTag = true;
}
if (!success_geoTag) {
getLastLocation();
fetchLocationAndCheckGeoFence();
}
checkgpsEnableDevice();
// checkgpsEnableDevice();
getMid();
}
private void checkgpsEnableDevice() {
/*private void checkgpsEnableDevice() {
if (!hasGPSDevice(this)) {
Toast.makeText(this, "Gps not Supported", Toast.LENGTH_SHORT).show();
}
@@ -608,7 +611,7 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
}
private void startLocationUpdates(LocationRequest locationRequest) {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
locationCallback = new LocationCallback() {
@Override
@@ -617,8 +620,10 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
for (Location location : locationResult.getLocations()) {
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
if(location.getAccuracy()<80){
lat = location.getLatitude();
lon = location.getLongitude();
}
}
}
}
@@ -634,14 +639,13 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
}
private boolean hasGPSDevice(Context context) {
final LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (mgr == null) return false;
final List<String> providers = mgr.getAllProviders();
if (providers == null) return false;
return providers.contains(LocationManager.GPS_PROVIDER);
}
}*/
private void DownloadJCP(final Context context, final ProgressDialog loading) {
try {
@@ -675,8 +679,9 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
jcpObject = new Gson().fromJson(data, JCPGetterSetter.class);
db.open();
if (jcpObject != null && db.insertJCPData(jcpObject)) {
Log.d("jcpdatanew","jcp data inserted");
/// checking GeoFencing
getLastLocation();
fetchLocationAndCheckGeoFence();
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")) {
@@ -832,7 +837,7 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
boolean allPermissionsGranted = Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.CAMERA)) && Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_NETWORK_STATE)) && Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_COARSE_LOCATION)) && Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_FINE_LOCATION)) && Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.READ_PHONE_STATE));
if (allPermissionsGranted) {
getLastLocation();
fetchLocationAndCheckGeoFence();
} else {
//test("", "Some permissions are not granted ask again ");
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_NETWORK_STATE) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) {
@@ -858,7 +863,46 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
}
}
private void getLastLocation() {
private void fetchLocationAndCheckGeoFence() {
if (isLocationFetching) return; // prevent multiple calls
isLocationFetching = true;
locationLoader.setVisibility(View.VISIBLE);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
);
locationEngine.start(new LocationEngine.LocationResultListener() {
@Override
public void onLocationReady(Location location, float accuracy) {
isLocationFetching = false;
locationLoader.setVisibility(View.GONE);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
lat = location.getLatitude();
lon = location.getLongitude();
Log.d("GeoFence", "Lat: " + lat + ", Lon: " + lon + ", Acc: " + accuracy);
// 🔥 Pass accuracy also
checkingGeoFencing(getMid(), accuracy);
}
@Override
public void onFailure(String msg) {
isLocationFetching = false;
locationLoader.setVisibility(View.GONE);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
Toast.makeText(StoreImageActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
}
/*private void fetchLocationAndCheckGeoFence() {
if (fusedLocationClient == null) {
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
@@ -869,7 +913,7 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
return;
}
// First, try to get the last known location
fusedLocationClient.getLastLocation()
fusedLocationClient.fetchLocationAndCheckGeoFence()
.addOnSuccessListener(location -> {
if (location != null) {
lat = location.getLatitude();
@@ -884,38 +928,74 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
// 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)
/*private void requestNewLocation() {
LocationRequest locationRequest = new LocationRequest.Builder(
Priority.PRIORITY_HIGH_ACCURACY, 2000)
.setMinUpdateIntervalMillis(1000)
.setMaxUpdateDelayMillis(3000)
.setMinUpdateDistanceMeters(0f)
.setWaitForAccurateLocation(true)
.build();
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(@NonNull LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
Log.d("Location", "Lat: " + lat + ", Lng: " + lon + " (new)");
checkingGeoFencing(getMid());
stopLocationUpdates(); // Stop updates after first valid location
break;
float accuracy = location.getAccuracy();
Log.d("Location", "Lat: " + location.getLatitude()
+ ", Lng: " + location.getLongitude()
+ ", Accuracy: " + accuracy);
// 🎯 IMPORTANT: Accept only accurate location
if (accuracy <= 80) {
lat = location.getLatitude();
lon = location.getLongitude();
Log.d("Location", "Accurate location received ✅");
checkingGeoFencing(getMid(),accuracy);
stopLocationUpdates(); // stop after good fix
break;
} else {
Log.d("Location", "Waiting for better accuracy...");
}
}
}
}
};
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
!= PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
checkAndRequestPermissions();
return;
}
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());
}
fusedLocationClient.requestLocationUpdates(
locationRequest,
locationCallback,
Looper.getMainLooper()
);
// ⏱ OPTIONAL: timeout (avoid infinite wait)
new android.os.Handler().postDelayed(() -> {
Log.d("Location", "Timeout reached ⏳");
stopLocationUpdates();
}, 10000); // 10 seconds max
}*/
private void stopLocationUpdates() {
if (fusedLocationClient != null && locationCallback != null) {
@@ -926,7 +1006,7 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
@Override
public void onDestroy() {
super.onDestroy();
// stopLocationUpdates();
// stopLocationUpdates();
if (loading != null && loading.isShowing()) {
loading.dismiss();
}
@@ -938,19 +1018,27 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
stopLocationUpdates();
}
private void checkingGeoFencing(JourneyPlan jcp) {
private void checkingGeoFencing(JourneyPlan jcp, float accuracy) {
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());
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());
int adjustedDistance = current_dist_from_store_using_lat - (int) accuracy;
Log.d("GeoFence", "Actual: " + current_dist_from_store_using_lat +
" Accuracy: " + accuracy +
" Adjusted: " + adjustedDistance);
Log.d("TagLoc", "Radius " + distance + "\nCurrent dist " + current_dist_from_store_using_lat);
if (current_dist_from_store_using_lat > distance) {
// if (current_dist_from_store_using_lat > distance) {
if (adjustedDistance > 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())) {
if (isFinishing() || isDestroyed()) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
@@ -964,10 +1052,11 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
}
}
} else {
if (isFinishing() || (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1 && isDestroyed())) {
if (isFinishing() || isDestroyed()) {
return;
}
db.open();
Log.d("jcpdata", jcp.getGeoTag());
if (jcp.getGeoTag() != null && !jcp.getGeoTag().equalsIgnoreCase(CommonString.KEY_Y) && !isGeoTagAlertShown) {
isGeoTagAlertShown = true;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
@@ -989,5 +1078,6 @@ public class StoreImageActivity extends AppCompatActivity implements View.OnClic
}
}
}
@@ -260,7 +260,7 @@ public class TabLoginActivity extends AppCompatActivity implements View.OnClickL
try {
PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0);
String version = pInfo.versionName;
versioncode_txt.setText("Version : " + version);
versioncode_txt.setText("Version : " + version +"-T1");
} catch (PackageManager.NameNotFoundException e) {
e.fillInStackTrace();
versioncode_txt.setText("Version : 0.0");
@@ -329,7 +329,7 @@ public class TabLoginActivity extends AppCompatActivity implements View.OnClickL
jsonObject.put("CounterId", counterId);
jsonObject.put("Latitude", lat);
jsonObject.put("Longitude", lon);
jsonObject.put("Appversion", app_ver);
jsonObject.put("Appversion", app_ver +"-T1");
jsonObject.put("Attmode", "0");
jsonObject.put("Networkstatus", "0");
jsonObject.put("ModelNumber", model);
@@ -31,6 +31,7 @@ import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.cpm.lorealbaMabeline.LocationEngine;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
@@ -106,44 +107,97 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
geocoder = new Geocoder(this);
declaration();
fab.setOnClickListener(view -> {
/*fab.setOnClickListener(view -> {
try {
startLocationUpdates();
if (!img_str.isEmpty()) {
if (db.InsertSTOREgeotag(jcpGetset.getStoreId().toString(), counter_id, jcpGetset.getBID().toString(), username, latitude, longitude, img_str) > 0) {
img_str = "";
if (checkNetIsAvailable(view.getContext())) {
new GeoTagUpload().execute();
} else {
AlertandMessages.showToastMsg(context, getResources().getString(R.string.nonetwork));
}
} else {
AlertandMessages.showToastMsg(context, "Error in saving Geotag");
}
startLocationUpdates(true);
} else {
AlertandMessages.showToastMsg(view.getContext(), getResources().getString(R.string.takeimage));
}
} catch (Exception e) {
e.fillInStackTrace();
}
});*/
fab.setOnClickListener(view -> {
try {
if (!img_str.isEmpty()) {
LocationEngine engine = new LocationEngine(this);
engine.start(new LocationEngine.LocationResultListener() {
@Override
public void onLocationReady(Location location, float accuracy) {
// Validate location
if (location == null) {
AlertandMessages.showToastMsg(context, "Unable to fetch location,Please try later");
return;
}
// Accuracy check (important for geofencing)
if (accuracy > 80) {
AlertandMessages.showToastMsg(context, "Fetching accurate location, please wait...");
return;
}
latitude = location.getLatitude();
longitude = location.getLongitude();
// Lat/Lng validation
if (latitude == 0.0 || longitude == 0.0) {
AlertandMessages.showToastMsg(context, "Invalid location, please try again");
return;
}
Log.d("GeoTag", "Acc: " + accuracy +","+ latitude + ","+longitude);
updateMapWithLocation(latitude, longitude);
// 🔥 Save geotag
if (db.InsertSTOREgeotag(
jcpGetset.getStoreId().toString(),
counter_id,
jcpGetset.getBID().toString(),
username,
latitude,
longitude,
img_str) > 0) {
if (checkNetIsAvailable(context)) {
new GeoTagUpload().execute();
} else {
AlertandMessages.showToastMsg(context, getString(R.string.nonetwork));
}
} else {
AlertandMessages.showToastMsg(context, "Error in saving Geotag");
}
}
@Override
public void onFailure(String msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
});
} else {
AlertandMessages.showToastMsg(view.getContext(), getString(R.string.takeimage));
}
} catch (Exception e) {
e.printStackTrace();
}
});
camera_fab.setOnClickListener(view -> {
try {
if (checkNetIsAvailable(view.getContext())) {
if (latitude != 0.0 && longitude != 0.0) {
_pathforcheck = jcpGetset.getStoreId().toString() + "-" + jcpGetset.getCounterId().toString() +
"-" + jcpGetset.getBID().toString() + "_GeoTag-" + jcpGetset.getVisitDate().replace("/", "")
+ "_" + getCurrentTime().replace(":", "") + ".jpg";
_path = CommonString.getImagesFolder(context) + _pathforcheck;
CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR);
} else {
AlertandMessages.showToastMsg(context, "Please wait for location");
}
if (latitude != 0.0 && longitude != 0.0) {
_pathforcheck = jcpGetset.getStoreId().toString() + "-" + jcpGetset.getCounterId().toString() +
"-" + jcpGetset.getBID().toString() + "_GeoTag-" + jcpGetset.getVisitDate().replace("/", "")
+ "_" + getCurrentTime().replace(":", "") + ".jpg";
_path = CommonString.getImagesFolder(context) + _pathforcheck;
CommonFunctions.startAnncaCameraActivity(context, _path, null, false, CommonString.CAMERA_FACE_REAR);
} else {
AlertandMessages.showToastMsg(context, getResources().getString(R.string.nonetwork));
AlertandMessages.showToastMsg(context, "Please wait for location");
}
} catch (Exception e) {
e.printStackTrace();
e.fillInStackTrace();
}
});
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
@@ -170,7 +224,6 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
if (distance > 10) {
previousLatitude = latitude;
previousLongitude = longitude;
updateMapWithLocation(latitude, longitude);
}
}
@@ -179,25 +232,60 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
}
};
}
private void startLocationUpdates() {
LocationRequest locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 5000)
.setMinUpdateIntervalMillis(3000)
private void startLocationUpdates(boolean save) {
LocationRequest locationRequest = new LocationRequest.Builder(
Priority.PRIORITY_HIGH_ACCURACY, 2000)
.setMinUpdateIntervalMillis(1000)
.setMaxUpdateDelayMillis(3000)
.setWaitForAccurateLocation(true)
.setMaxUpdateDelayMillis(6000)
.build();
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);
}
});
fusedLocationClient.requestLocationUpdates(
locationRequest,
new LocationCallback() {
@Override
public void onLocationResult(@NonNull LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
if (location != null) {
float accuracy = location.getAccuracy();
Log.d("Location", "Accuracy: " + accuracy);
// Only accept good accuracy
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("Location", "Accuracy: " + accuracy +","+ latitude +","+ longitude);
previousLatitude = latitude;
previousLongitude = longitude;
if (save){
runOnUiThread(() -> {
if (db.InsertSTOREgeotag(jcpGetset.getStoreId().toString(), counter_id, jcpGetset.getBID().toString(), username, latitude, longitude, img_str) > 0) {
if (checkNetIsAvailable(context)) {
new GeoTagUpload().execute();
} else {
AlertandMessages.showToastMsg(context, getResources().getString(R.string.nonetwork));
}
} else {
AlertandMessages.showToastMsg(context, "Error in saving Geotag");
}
});
}
updateMapWithLocation(latitude, longitude);
stopLocationUpdates(); // stop after good fix
break;
}
}
}
},
Looper.getMainLooper()
);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
@@ -205,6 +293,19 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
}
}
private void stopLocationUpdates() {
if (fusedLocationClient != null && locationCallback != null) {
fusedLocationClient.removeLocationUpdates(locationCallback);
}
}
@Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
private void updateMapWithLocation(double lat, double lon) {
if (geocoder != null && mMap != null) {
Log.e("jeevanp", "" + lat);
@@ -248,29 +349,69 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
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) {
// REMOVE this (causes 0,0 jump)
// mMap.moveCamera(...)
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();
// Use LocationEngine instead
fetchMapLocation();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_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)) {
}
private void fetchMapLocation() {
LocationEngine engine = new LocationEngine(this);
engine.start(new LocationEngine.LocationResultListener() {
@Override
public void onLocationReady(Location location, float accuracy) {
if (location == null) return;
// 🎯 Optional: accuracy check
if (accuracy > 80) {
Log.d("Map", "Waiting for better accuracy...");
return;
}
latitude = location.getLatitude();
longitude = location.getLongitude();
previousLatitude = latitude;
previousLongitude = longitude;
Log.d("Map", "Lat: " + latitude + ", Lng: " + longitude + ", Acc: " + accuracy);
updateMapWithLocation(latitude, longitude);
}
@Override
public void onFailure(String msg) {
Toast.makeText(GeoTaggingActivity.this, msg, Toast.LENGTH_SHORT).show();
}
});
}
@@ -293,7 +434,7 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
mMap.getUiSettings().setMyLocationButtonEnabled(true);
}
}
startLocationUpdates();
startLocationUpdates(false);
} else {
Toast.makeText(this, "Location permissions are required for geotagging", Toast.LENGTH_LONG).show();
}
@@ -303,13 +444,13 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
@Override
protected void onResume() {
super.onResume();
checkgpsEnableDevice();
//checkgpsEnableDevice();
}
@Override
protected void onStart() {
super.onStart();
startLocationUpdates();
startLocationUpdates(false);
}
@@ -399,9 +540,9 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
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();
@@ -433,7 +574,6 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
} else {
return errormsg;
}
}
private @NonNull String getString() throws JSONException {
@@ -442,7 +582,6 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
JSONObject obj = getJsonObject(j);
topUpArray.put(obj);
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("MID", jcpGetset.getMID() != null ? jcpGetset.getMID() : 0);
jsonObject.put("Keys", "GeoTag");
@@ -454,7 +593,7 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
@NonNull
private JSONObject getJsonObject(int j) throws JSONException {
JSONObject obj = new JSONObject();
obj.put("UserId",username);
obj.put("UserId", username);
obj.put("StoreId", geotaglist.get(j).getStoreid());
obj.put("CounterId", geotaglist.get(j).getCounterId());
obj.put("bID", geotaglist.get(j).getBid());
@@ -510,9 +649,8 @@ public class GeoTaggingActivity extends AppCompatActivity implements OnMapReadyC
settingsClient.checkLocationSettings(builder.build()).addOnSuccessListener(locationSettingsResponse -> {
// All location settings are satisfied. You can request location updates here.
}).addOnFailureListener(e -> {
if (e instanceof ResolvableApiException) {
if (e instanceof ResolvableApiException resolvable) {
try {
ResolvableApiException resolvable = (ResolvableApiException) e;
resolvable.startResolutionForResult((Activity) this, REQUEST_LOCATION);
} catch (IntentSender.SendIntentException sendEx) {
// Ignore the error.
@@ -25,6 +25,13 @@
android:gravity="center"
android:orientation="vertical">
<ProgressBar
android:id="@+id/locationLoader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone"/>
<ImageView
android:id="@+id/img_selfie"
android:layout_width="match_parent"
@@ -25,6 +25,13 @@
android:layout_margin="@dimen/margin_30dp"
android:orientation="vertical">
<ProgressBar
android:id="@+id/locationLoader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone"/>
<ImageView
android:id="@+id/img_selfie"
android:layout_width="match_parent"