#android #kotlin
Вопрос:
Я написал очень простое приложение для уведомлений о срабатывании геозоны в Котлине, следуя инструкциям на официальной странице, чтобы проверить, как работает геозона. Но когда я использовал эмуляцию, ничего не срабатывало. Почему это так? (Я уже объявил получателя в манифесте)
//Main activity: class MainActivity : AppCompatActivity() { lateinit var geofencingClient: GeofencingClient @SuppressLint("LongLogTag") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) geofencingClient = LocationServices.getGeofencingClient(this) val latitude = 37.3448 val longitude = -122.0476 val radius = 100f val key = "whatever" val geofence = Geofence.Builder() .setRequestId(key) .setCircularRegion(latitude, longitude, radius) .setExpirationDuration(Geofence.NEVER_EXPIRE) .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT) .build() val geofenceRequest = GeofencingRequest.Builder().setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER).addGeofence(geofence).build() val intent = Intent(this, GeofenceBroadcastReceiver::class.java) .putExtra("key", key) .putExtra("message", "Geofence alert -- latitude: $latitude, longitude: $longitude") val pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT) if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_BACKGROUND_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION), GEOFENCE_LOCATION_REQUEST_CODE) } else { Log.d("GeofenceBroadcastReceiver", "YES!!!!!!!!!!!!!!!!!!!!!!") geofencingClient.addGeofences(geofenceRequest, pendingIntent) } } } //GeofenceBroadcastReceiver: class GeofenceBroadcastReceiver : BroadcastReceiver() { @SuppressLint("LongLogTag") override fun onReceive(context: Context?, intent: Intent?) { val geofencingEvent = GeofencingEvent.fromIntent(intent) if (geofencingEvent.hasError()) { val errorMessage = GeofenceStatusCodes .getStatusCodeString(geofencingEvent.errorCode) Log.e("GeofenceBroadcastReceiver", errorMessage) return } val geofencingTransition = geofencingEvent.geofenceTransition when (geofencingTransition) { Geofence.GEOFENCE_TRANSITION_ENTER -gt; { Log.d("GeofenceBroadcastReceiver", "IN!!!!!!!!!!!!!!!!!!!!!!") Toast.makeText(context, "IN!!!!!!!!!!!!!!!!!!!!!!", Toast.LENGTH_LONG).show() showNotification(context, "IN!!!!!!!") } Geofence.GEOFENCE_TRANSITION_EXIT -gt; { Log.d("GeofenceBroadcastReceiver", "OUT!!!!!!!!!!!!!!!!!!") Toast.makeText(context, "OUT!!!!!!!!!!!!!!!!!!!!!!", Toast.LENGTH_LONG).show() showNotification(context, "OUT!!!!!!!!!") } else -gt; { Log.d("GeofenceBroadcastReceiver", "why!!!!!!!!!!!!!!!!!!") } } } private fun showNotification(context: Context?, message: String) { val CHANNEL_ID = "REMINDER_NOTIFICATION_CHANNEL" var notificationId = 1589 notificationId = Random(notificationId).nextInt(1, 30) val notificationBuilder = NotificationCompat.Builder(context!!.applicationContext, CHANNEL_ID) .setContentTitle(context.getString(R.string.app_name)) .setContentText(message) .setStyle(NotificationCompat.BigTextStyle().bigText(message)) .setPriority(NotificationCompat.PRIORITY_DEFAULT) val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT gt;= Build.VERSION_CODES.O) { val channel = NotificationChannel( CHANNEL_ID, context.getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT ).apply { description = context.getString(R.string.app_name) } notificationManager.createNotificationChannel(channel) } notificationManager.notify(notificationId, notificationBuilder.build()) } }
Даже без уведомления ничего не срабатывает. Связано ли это с моими настройками в эмуляторе? (Широта и долгота, которые я использую для тестирования своего приложения, связаны с точкой в эмуляторе, и я всегда начинаю или заканчиваю маршрут с ней, чтобы протестировать приложение)