Android, после обнаружения GeofencingEvent в IntentService я хочу быть перенаправлен на мой фрагмент шоу - PullRequest
0 голосов
/ 11 марта 2020

Мое android приложение геолокации меня, и я определил геозоны вокруг меня

Когда пользователь входит в геозону, мой GeofenceIntentService дает мне идентификатор этой геозоны

Я хотел бы, чтобы пользователь быть перенаправленным на детали геозоны (showFragment)

Я не знаю, как я могу перенаправить на фрагмент из своего намерения

Я попытался пройти через redirectActivity, но я использую компонент навигации и Я не знаю, как перейти от действия к фрагменту

Какое самое чистое решение

Вызов Geofence из фрагмента

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        getLocation()


        geofenceManager.createGeoFence()
}
class GeofenceIntentService : IntentService("TravauxGeofenceIntentService") {

    override fun onHandleIntent(intent: Intent?) {
        val geofenceEvent = GeofencingEvent.fromIntent(intent)
        if (geofenceEvent.hasError()) {
            return
        }
        val geofenceTransition = geofenceEvent.geofenceTransition
        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_DWELL) {
            return
        }
        if (geofenceEvent.triggeringGeofences == null) {
            return
        }
        for (triggeringGeofence in geofenceEvent.triggeringGeofences) {
            if (triggeringGeofence.requestId == "mageofence") {
                goTo(geofenceTransition, triggeringGeofence.requestId)
            }
        }
    }

    /**
     * HOW TO REDIRECT 
     */
    private fun goTo(geofenceTransition: Int, idAvaloir: String) {
        val intent = Intent(this, RedirectActivity::class.java).apply {
            putExtra("id", idAvaloir)
        }
        startActivity(intent)
    }
}

class RedirectActivity : AppCompatActivity() {

    private val avaloirModel: AvaloirViewModel by viewModel()
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val avaloirId = intent.getStringExtra("id")
        if (avaloirId != null && avaloirId.isNotEmpty()) {
            avaloirModel.getAvaloirById(avaloirId.toInt())
            intent = Intent(this, ShowFragment::class.java)
            startActivity(intent)
            findNavController(R.id.nav_host_fragment).navigate(R.id.action_homeFragment_to_addFragment)
        }

    }
}
class GeofenceManager(context: Context) {
    //on recurpe TravauxApp
    private val appContext = context.applicationContext
    private val geofencingClient = LocationServices.getGeofencingClient(appContext)
    private val geofenceList = mutableListOf<Geofence>()

    fun addGeofenceToList(
        latitude: Double,
        longitude: Double,
        requestId: String,
        radiusMeter: Float = 1000.0f
    ) {
        geofenceList.add(
            Geofence.Builder()
                .setRequestId(requestId)
                .setExpirationDuration(Geofence.NEVER_EXPIRE)
                .setCircularRegion(
                    latitude,
                    longitude,
                    radiusMeter
                )
                .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
                .build()
        )
    }

    fun createGeoFence() {
        val task = geofencingClient.addGeofences(geoFencingRequest(), geofencePendingIntent)
        task.addOnSuccessListener {
            Timber.w("zeze pending succes")
        }
        task.addOnFailureListener {
            Timber.w("zeze pending error: " + it.message)
        }
    }

    val geofencePendingIntent: PendingIntent by lazy {
        val intent = Intent(appContext, GeofenceIntentService::class.java)
        //PendingIntent.getBroadcast()
        PendingIntent.getService(
            appContext,
            0,
            intent,
            PendingIntent.FLAG_UPDATE_CURRENT
        )
    }

    private fun geoFencingRequest(): GeofencingRequest? {
        if (geofenceList.size < 1)
            return null

        return GeofencingRequest.Builder()
            .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)//si on est a l'interieur on veut declenche
            .addGeofences(geofenceList)
            .build()
    }

    fun removeAllGeofences() {
        geofencingClient.removeGeofences(geofencePendingIntent)
        geofenceList.clear()
    }

}
...