Геозона не срабатывает на AndroidAndroid

Форум для тех, кто программирует под Android
Ответить
Anonymous
 Геозона не срабатывает на Android

Сообщение Anonymous »

Я разрабатываю приложение для Android, которое автоматически инициирует телефонный звонок всякий раз, когда я вхожу в определенную геозону. Я подтвердил, что BroadcastReceiver и компоненты фоновой службы работают должным образом. BroadcastReceiver способен принимать широковещательные сообщения при срабатывании, и служба работает без каких-либо проблем. Однако сама геозона, похоже, не активируется должным образом — она не срабатывает при входе в указанную границу местоположения и в результате не может отправить ожидаемое широковещательное сообщение в BroadcastReceiver.
Мой код:
public class GeofenceService extends Service {
private static final String TAG = "GeofenceService";
private static final String CHANNEL_ID = "GeofenceChannel";
private GeofencingClient geofencingClient;
private List geofenceList;
private List geofenceIds = new ArrayList();

@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
startForeground(1, getNotification());

// Initialize GeofencingClient and geofences
geofencingClient = LocationServices.getGeofencingClient(this);
geofenceList = new ArrayList();

// Add your geofence(s) here
setupGeofences();
Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_SHORT).show();
}

@SuppressLint("MissingPermission")
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "Service started");

// Start geofencing
addGeofences();

return START_STICKY; // Ensure the service is restarted if killed
}

private Notification getNotification() {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_IMMUTABLE);

return new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("Geofencing Service")
.setContentText("Monitoring geofence...")
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build();
}

private void createNotificationChannel() {
NotificationChannel serviceChannel = new NotificationChannel(
CHANNEL_ID,
"Geofencing Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
);

NotificationManager manager = getSystemService(NotificationManager.class);
if (manager != null) {
manager.createNotificationChannel(serviceChannel);
}
}

@Override
public IBinder onBind(Intent intent) {
return null; // We don't provide binding, so return null
}

private void setupGeofences() {
// Define geofence(s) here
geofenceList.add(new Geofence.Builder()
.setRequestId("home") // Unique ID for the geofence
.setCircularRegion(
50.09886,
50.88337,
100
)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
.build());
geofenceIds.add("home");
}

@SuppressLint("MissingPermission")
private void addGeofences() {
GeofencingRequest geofencingRequest = new GeofencingRequest.Builder()
.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
.addGeofences(geofenceList) // Add geofences to the request
.build();

Intent intent = new Intent(this, GeofenceBroadcastReceiver.class); // BroadcastReceiver to handle geofence transitions
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

geofencingClient.addGeofences(geofencingRequest, pendingIntent)
.addOnSuccessListener(aVoid -> Log.d(TAG, "Geofences added successfully"))
.addOnFailureListener(e -> Log.e(TAG, "Failed to add geofences", e));
}

private void removeGeofences(List geofenceIds) {
geofencingClient.removeGeofences(geofenceIds);
Log.d(TAG, "removeGeofences: removed");
}

@Override
public void onDestroy() {
super.onDestroy();
removeGeofences(geofenceIds);
Log.d(TAG, "Service destroyed");
// Clean up any resources here
Toast.makeText(getApplicationContext(), "Service Stopped", Toast.LENGTH_SHORT).show();
}
}


Подробнее здесь: https://stackoverflow.com/questions/791 ... on-android
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Android»