Android Geofencing: Konum Tabanlı Uyarı Uygulaması Kodlama

Geofencing, belirli bir coğrafi alan etrafına sanal bir sınır çizer ve kullanıcı o alana girdiğinde ya da çıktığında uyarı gönderir. Örneğin bir mağaza yakınına geldiğinde indirim bildirimi almak gibi. Android'de bunu LocationManager ve Broadcast Receiver ile yapabilirsin.

İlk olarak AndroidManifest.xml dosyasına izinleri ekle:

1<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
2<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
3<uses-permission android:name="android.permission.INTERNET" />

Konum izinlerini runtime'da istemeyi de unutma. Şimdi Geofencing servisi oluştur:

1import android.content.Context;
2import android.content.Intent;
3import android.location.LocationManager;
4import android.location.Location;
5import android.os.Handler;
6import android.os.Looper;
7
8public class GeofenceService {
9private LocationManager locationManager;
10private Context context;
11private double targetLat = 41.0082; // İstanbul Taksim
12private double targetLon = 28.9784;
13private float radiusMeters = 100; // 100 metre çapında alan
14
15public GeofenceService(Context context) {
16this.context = context;
17this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
18}
19
20public void startMonitoring() {
21Handler handler = new Handler(Looper.getMainLooper());
22handler.post(() -> {
23try {
24Location lastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
25if (lastLocation!= null) {
26checkGeofence(lastLocation);
27}
28} catch (SecurityException e) {
29e.printStackTrace();
30}
31});
32}
33
34private void checkGeofence(Location currentLocation) {
35float distance = currentLocation.distanceTo(createTargetLocation());
36
37if (distance < radiusMeters) {
38sendNotification("Mağazaya hoş geldiniz! Bugün %20 indirim var.");
39} else {
40sendNotification("Mağazadan uzaktasın.");
41}
42}
43
44private Location createTargetLocation() {
45Location target = new Location(LocationManager.GPS_PROVIDER);
46target.setLatitude(targetLat);
47target.setLongitude(targetLon);
48return target;
49}
50
51private void sendNotification(String message) {
52Intent intent = new Intent(context, NotificationReceiver.class);
53intent.putExtra("message", message);
54context.sendBroadcast(intent);
55}
56}

Broadcast Receiver ile bildirimi göster:

Reklam · TEST
AdSense Test ReklamıYazı arası (gönderi içi) · Yazı arası
1import android.content.BroadcastReceiver;
2import android.content.Context;
3import android.content.Intent;
4import android.widget.Toast;
5
6public class NotificationReceiver extends BroadcastReceiver {
7@Override
8public void onReceive(Context context, Intent intent) {
9String message = intent.getStringExtra("message");
10Toast.makeText(context, message, Toast.LENGTH_LONG).show();
11}
12}

Activity'de servisi başlat:

1public class MainActivity extends AppCompatActivity {
2private GeofenceService geofenceService;
3
4@Override
5protected void onCreate(Bundle savedInstanceState) {
6super.onCreate(savedInstanceState);
7setContentView(R.layout.activity_main);
8
9geofenceService = new GeofenceService(this);
10geofenceService.startMonitoring();
11}
12}

Beklenen çıktı: Kullanıcı hedef koordinatlara 100 metre yaklaştığında "Mağazaya hoş geldiniz! Bugün %20 indirim var." Toast bildirimi görünür.

Sık yapılan hata: LocationManager.getLastKnownLocation() null döndürebilir. Bunun yerine Google Play Services'in FusedLocationProviderClient'ını kullanmak daha güvenilir. Gerçek uygulamada, konum güncellemelerini sürekli dinlemek için LocationListener ekle ve Service'i arka planda çalıştır. Ayrıca kullanıcının konumunu sık sorgulamak pili tüketir; güncelleme aralığını makul tut.

Reklam · TEST
AdSense Test ReklamıGönderi altı · Görüntülü
konu hakkında tepkinizi verebilirsiniz
  • adlı kullanıcıya yanıt verdi
    kayipparmaklik

    ama google apisi de internet bağlantısı gerektiriyor ya offline çalışması gerekirse LocationManager daha iyi değil mi

  • kirmizibisiklet

    geofencingi LocationManager ile yapan çok oluyor da ben ama bence Googleın kendi Geofencing APIsini kullansan daha rahat olur LocationManager manuel kontrol gerektiriyor hafıza da daha çok çekiyor APIde zaten hazır fenceler ve eventler var sen sadece PendingIntenti yakala

    1val geofencingClient = LocationServices.getGeofencingClient(context)
    2val geofence = Geofence.Builder().setRequestId("magaza_1").setCircularRegion(40.7128, -74.0060, 100f) // 100 metre.setExpirationDuration(Geofence.NEVER_EXPIRE).setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER).build()
    3
    4val request = GeofencingRequest.Builder().addGeofence(geofence).build()
    5geofencingClient.addGeofences(request, getPendingIntent()).addOnSuccessListener {
    6Log.d("Geofence", "Eklendi")
    7}

    Geri kalan iş BroadcastReceiverda gelen GEOFENCE_TRANSITION_ENTER eventini yakala ve bildirim göster LocationManagerdan çok daha verimli