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;78public class GeofenceService {9private LocationManager locationManager;10private Context context;11private double targetLat = 41.0082; // İstanbul Taksim12private double targetLon = 28.9784;13private float radiusMeters = 100; // 100 metre çapında alan1415public GeofenceService(Context context) {16this.context = context;17this.locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);18}1920public 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}3334private void checkGeofence(Location currentLocation) {35float distance = currentLocation.distanceTo(createTargetLocation());3637if (distance < radiusMeters) {38sendNotification("Mağazaya hoş geldiniz! Bugün %20 indirim var.");39} else {40sendNotification("Mağazadan uzaktasın.");41}42}4344private Location createTargetLocation() {45Location target = new Location(LocationManager.GPS_PROVIDER);46target.setLatitude(targetLat);47target.setLongitude(targetLon);48return target;49}5051private 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:
1import android.content.BroadcastReceiver;2import android.content.Context;3import android.content.Intent;4import android.widget.Toast;56public class NotificationReceiver extends BroadcastReceiver {7@Override8public 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;34@Override5protected void onCreate(Bundle savedInstanceState) {6super.onCreate(savedInstanceState);7setContentView(R.layout.activity_main);89geofenceService = 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.
2 yorum
ama google apisi de internet bağlantısı gerektiriyor ya offline çalışması gerekirse LocationManager daha iyi değil mi
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
Geri kalan iş BroadcastReceiverda gelen GEOFENCE_TRANSITION_ENTER eventini yakala ve bildirim göster LocationManagerdan çok daha verimli