я делаю проект, который использует геозону, я написал свой код в kotlin, когда я тестировал его, он работал отлично, но на следующий день он не работает, мне нужно перезагрузить телефон, чтобы получить работу геозоны ( переход запущен), вы можете мне помочь, ребята?
я не использую широковещательный приемник, но использую службу intentservice, также я планирую запустить его на фоне
MainActivity.kt
private lateinit var mGeofencingClient: GeofencingClient
private var mGeofenceList: ArrayList<Geofence> = ArrayList()
private val geofencingRequest: GeofencingRequest
get() {
return GeofencingRequest.Builder().apply {
setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
addGeofences(mGeofenceList)
}.build()
}
private val geofencePendingIntent: PendingIntent by lazy {
val intent = Intent(this, GeofenceTransitionsIntentService::class.java)
PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
mySharedPreferences = MySharedPreferences(applicationContext)
mGeofencingClient = LocationServices.getGeofencingClient(this)
removeGeofences()
val sdf = SimpleDateFormat("dd-MM-yyyy")
val currentDate = sdf.format(Date())
val lastUpdateGeofence = mySharedPreferences.getLastUpdateGeofence()
if (currentDate != lastUpdateGeofence){
presenter.requestDataForGeofence(dataUser.userId)
}
}
override fun onFetchOutletSuccess(data: MainResponse) {
populateGeofenceList(data.result)
}
override fun toastError(error: String) {
toast(error)
Log.d("MainActivity", error)
}
private fun populateGeofenceList(data: List<Schedule>) {
mGeofenceList.clear()
for (schedule in data) {
mGeofenceList.add(
Geofence.Builder()
.setRequestId(schedule.name)
.setCircularRegion(
schedule.latitude.toDouble(),
schedule.longitude.toDouble(),
Constants.GEOFENCE_RADIUS_IN_METERS
)
.setExpirationDuration(Constants.GEOFENCE_EXPIRATION_IN_MILLISECONDS)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
.build()
)
}
addGeofences()
}
@SuppressLint("MissingPermission")
private fun addGeofences() {
if (!checkPermissions()) {
toastError(getString(R.string.insufficient_permissions))
return
}
Log.d(TAG, "Adding Geofences")
mGeofencingClient.addGeofences(geofencingRequest, geofencePendingIntent).run {
addOnSuccessListener {
toastError("Success adding Geofence")
}
addOnFailureListener {
val errorMessage = GeofenceErrorMessages.getErrorString(this@MainActivity, it)
toastError(errorMessage)
Log.e(TAG, errorMessage)
}
}
}
private fun removeGeofences() {
mGeofencingClient.removeGeofences(geofencePendingIntent).run {
addOnSuccessListener {
toastError("Success removing Geofence")
}
addOnFailureListener {
val errorMessage = GeofenceErrorMessages.getErrorString(this@MainActivity, it)
toastError(errorMessage)
Log.e(TAG, errorMessage)
}
}
}
TransisitionIntentService.kt
class GeofenceTransitionsIntentService : IntentService(TAG) {
private lateinit var detail: String
override fun onHandleIntent(intent: Intent?) {
val geofencingEvent = GeofencingEvent.fromIntent(intent)
if (geofencingEvent.hasError()) {
val errorMessage = GeofenceErrorMessages.getErrorString(this,
geofencingEvent.errorCode)
Log.e(TAG, errorMessage)
return
}
val geofenceTransition = geofencingEvent.geofenceTransition
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER || geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
val triggeringGeofences = geofencingEvent.triggeringGeofences
val geofenceTransitionDetails = getGeofenceTransitionDetails(geofenceTransition,
triggeringGeofences)
when (geofenceTransition) {
Geofence.GEOFENCE_TRANSITION_ENTER -> {
detail = "$geofenceTransitionDetails"
sendNotification(detail)
}
Geofence.GEOFENCE_TRANSITION_EXIT -> {
detail = "$geofenceTransitionDetails " sendNotification(detail)
}
}
} else {
Log.e(TAG, getString(R.string.geofence_transition_invalid_type, geofenceTransition))
}
}
private fun getGeofenceTransitionDetails(
geofenceTransition: Int,
triggeringGeofences: List<Geofence>): String {
val geofenceTransitionString = getTransitionString(geofenceTransition)
val triggeringGeofencesIdsList = ArrayList<String>()
for (geofence in triggeringGeofences) {
triggeringGeofencesIdsList.add(geofence.requestId)
}
val triggeringGeofencesIdsString = TextUtils.join(", ", triggeringGeofencesIdsList)
return "$geofenceTransitionString: $triggeringGeofencesIdsString"
}
private fun getTransitionString(transitionType: Int): String {
when (transitionType) {
Geofence.GEOFENCE_TRANSITION_ENTER -> return getString(R.string.geofence_transition_entered)
Geofence.GEOFENCE_TRANSITION_EXIT -> return getString(R.string.geofence_transition_exited)
else -> return getString(R.string.unknown_geofence_transition)
}
}
private fun sendNotification(notificationDetails: String) {
val mBuilder =
NotificationCompat.Builder(
applicationContext,
"notify_001"
)
val ii = Intent(applicationContext, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(applicationContext, 0, ii, 0)
val bigText = NotificationCompat.BigTextStyle()
bigText.bigText(notificationDetails)
bigText.setBigContentTitle("Apps")
bigText.setSummaryText("Notification")
mBuilder.setContentIntent(pendingIntent)
mBuilder.setSmallIcon(R.mipmap.logo)
mBuilder.setContentTitle("Apps")
mBuilder.setContentText(notificationDetails)
mBuilder.setStyle(bigText)
val mNotificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= 26) {
val channelId = "Your_channel_id"
val channel = NotificationChannel(
channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT
)
mNotificationManager.createNotificationChannel(channel)
mBuilder.setChannelId(channelId)
}
val int = (Date().time / 1000L % Int.MAX_VALUE).toInt()
mNotificationManager.notify(int, mBuilder.build())
}
companion object {
private val TAG = "GeofenceTransitionsIS"
}
}