Push-уведомления об обнаружении маяка, когда приложение не запущено / не убито - PullRequest
0 голосов
/ 16 октября 2018

Я начал изучать маяки и недавно начал использовать их в своих приложениях для Android.Но я не могу решить данную мне проблему: 1. Отображать push-уведомление всякий раз, когда мое устройство Android Oreo входит в область маяка.2. Отображать push-уведомление всякий раз, когда мое устройство Android Oreo выходит из области маяка

УСЛОВИЯ:

  • Уведомление должно отображаться, даже если приложение не открыто
  • Уведомление должно отображаться, даже если приложение убито
  • Не должно быть никаких задержек при отображении уведомления (т. Е. Уведомление должно отображаться немедленно, когда устройство входит и выходит из диапазона маяка)
  • Для диапазона одного маяка уведомление должно отображаться только один раз для входа и один раз для выхода.Только когда устройство входит в какой-либо другой диапазон, отличный от текущего диапазона, должно отображаться новое уведомление.

Это код для класса MyApplication

import android.app.*
import android.content.Context
import android.content.Intent
import android.os.Build
import android.support.v4.app.NotificationCompat
import android.util.Log
import com.estimote.coresdk.observation.region.beacon.BeaconRegion
import com.estimote.coresdk.recognition.packets.Beacon
import com.estimote.coresdk.service.BeaconManager
import java.util.*

class MyApplication : Application() {

    private var beaconManager: BeaconManager? = null
    val TAG = javaClass.name

    override fun onCreate() {
        super.onCreate()
        beaconManager = BeaconManager(applicationContext)


        beaconManager!!.setForegroundScanPeriod(1000, 0)

        beaconManager!!.setMonitoringListener(object : BeaconManager.BeaconMonitoringListener {

            override fun onExitedRegion(beaconRegion: BeaconRegion?) {
                showNotif("Exit", "Bye bye")
                Log.e(TAG, "Exit range")
            }

            override fun onEnteredRegion(beaconRegion: BeaconRegion?, beacons: MutableList<Beacon>?) {
                showNotif("Entry", "Hey there")
                Log.e(TAG, "Enter range")
            }
        })

        beaconManager!!.connect {
            beaconManager!!.startMonitoring(
                BeaconRegion(
                    "monitored region",
                    UUID.fromString("B9407F30-F5F8-466E-AFF9-25556B57FE6D"),
                    1,
                    1
                )
            )
        }
    }

    fun showNotif(title: String, text: String) {
        val notifyIntent = Intent(this, MainActivity::class.java)
        notifyIntent.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
        val pendingIntent: PendingIntent = PendingIntent.getActivities(
            this,
            0,
            arrayOf(notifyIntent),
            PendingIntent.FLAG_UPDATE_CURRENT
        )

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val mChannel = NotificationChannel("1", "Notify Channel", NotificationManager.IMPORTANCE_HIGH)
            val notification = Notification.Builder(this, "1")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle(title)
                .setContentText(text)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .build()
            //notification.defaults = notification.defaults or Notification.DEFAULT_SOUND
            val notificationManager: NotificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.createNotificationChannel(mChannel)
            notificationManager.notify(1, notification)
            startForegroundService(notifyIntent)

        } else {
            val notification = NotificationCompat.Builder(this,"1")
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setContentTitle(title)
                .setContentText(text)
                .setAutoCancel(true)
                .setContentIntent(pendingIntent)
                .build()
            //notification.defaults = notification.defaults or Notification.DEFAULT_SOUND
            val notificationManager: NotificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            notificationManager.notify(1, notification)
        }
    }
}

Этот код работает хорошов устройствах с версией меньше, чем Oreo.Но это не соответствует всем вышеупомянутым условиям в Орео.Я пытался использовать мониторинг, ранжирование, bootStrapNotifier и т. Д. Но каждый из них мог решить лишь немногие из вышеперечисленных условий, оставив остальные.Пожалуйста, кто-нибудь может мне помочь с кодом, который отвечает всем вышеперечисленным условиям

Заранее спасибо:)

...