public class MyForegroundServiceLocation extends Service {
private static final String CHANNEL_ID = "ForegroundServiceChannel";
private static final String TAG = "MyForegroundService";
private GeofencingClient geofencingClient;
private Handler handler;
private Runnable runnable;
code
Assistant
@Override
public void onCreate() {
super.onCreate();
geofencingClient = LocationServices.getGeofencingClient(this);
createNotificationChannel();
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
checkGeofenceStatus();
handler.postDelayed(this, 5000); // Check every 10 seconds
}
};
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@SuppressLint("ForegroundServiceType")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Foreground Service")
.setContentText("Monitoring geofencing")
.setSmallIcon(R.drawable.lockstazy)
.build();
startForeground(1, notification);
handler.post(runnable);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(runnable);
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Foreground Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager manager = getSystemService(NotificationManager.class);
if (manager != null) {
manager.createNotificationChannel(serviceChannel);
}
}
}
private void checkGeofenceStatus() {
Geofence geofence = new Geofence.Builder()
.setRequestId("GeofenceID")
.setCircularRegion(28.6359552, 77.3095424, 10) // Example coordinates and radius
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
.build();
GeofencingRequest geofencingRequest = new GeofencingRequest.Builder()
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
.addGeofence(geofence)
.build();
PendingIntent pendingIntent = getGeofencePendingIntent();
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Task<Void> geofenceTask = geofencingClient.addGeofences(geofencingRequest, pendingIntent);
geofenceTask.addOnSuccessListener(aVoid -> {
Toast.makeText(getApplicationContext(), "Geofencing setup successful", Toast.LENGTH_SHORT).show();
}).addOnFailureListener(e -> {
Toast.makeText(getApplicationContext(), "Geofencing setup failed: " + e.getMessage(), Toast.LENGTH_SHORT).show();
});
}
private PendingIntent getGeofencePendingIntent() {
Intent intent = new Intent(this, GeofenceBroadcastReceiver.class);
return PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
}
To display the geofenced area in red and your live location with a blue dot on a map, you'll need to create an Activity that includes a GoogleMap. Below are the steps and code to achieve this:
Set up Google Maps in your project:
Ensure you've added the Google Maps API key to your AndroidManifest.xml.
Add the required dependencies in your build.gradle file.
Create a new Activity (MapActivity) to display the map.
In MapActivity, implement the map and the geofence visualization.
Here's the detailed implementation:
1. Add Google Maps Dependencies and API Key
Add Dependencies in your app/build.gradle:
gradle
dependencies {
// Other dependencies
implementation 'com.google.android.gms:play-services-maps:18.0.2' // Use the latest version
implementation 'com.google.android.gms:play-services-location:21.0.1'
}
Add Permissions and API Key in your AndroidManifest.xml:
For devices running Android 6.0 (API level 23) and above, location permissions are requested at runtime.
This is handled in the getLocationPermission() method and onRequestPermissionsResult() callback in MapActivity.
6. Start MapActivity from Your Main Activity
In your main activity or wherever appropriate, start the MapActivity to display the map:
java
Intent intent = new Intent(this, MapActivity.class);
startActivity(intent);
Additional Considerations
Handling Permissions: Ensure your app handles cases where the user denies location permissions gracefully.
API Key Restrictions: Verify that your Google Maps API key is properly configured in the Google Cloud Console, and any restrictions are correctly set.
Testing on a Physical Device: Location services may not work accurately on emulators; it's recommended to test on a physical device.
Foreground Service and Map Activity Coordination: Since you have a foreground service (MyForegroundServiceLocation) running, make sure there are no conflicts between the service and the activity. The service can continue to run in the background while the activity handles the UI.
Summary
By following the steps above, your app will display:
Geofenced Area: Shown on the map as a red circle representing the area you have set for geofencing.
Live Location: Displayed as a blue dot, indicating the user's current position.
This visual representation will help users see their current location relative to the geofenced area.
Let me know if you have any questions or need further assistance!