Я делаю Сервис, используя Proximity Alert. Когда я нахожу в указанное c место, оповещение о близости должно быть активировано. Однако даже я проверил, что данные GPS (широта, долгота) были приняты правильно. В чем проблема? Я приложил коды.
Часть MyService.kt
package my.app
import android.annotation.SuppressLint
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.location.Criteria
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.os.Looper
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
val TAG = "MyAppTAG"
class MyService : Service() {
lateinit var receiver: MyReceiver
lateinit var lm: LocationManager
lateinit var dbHelper: DBHelper
override fun onBind(intent: Intent): IBinder? {
return null
}
@SuppressLint("MissingPermission")
override fun onCreate() {
super.onCreate()
val sharedPreferences = getSharedPreferences(packageName + "_preferences", Context.MODE_PRIVATE)
val lm = getSystemService(Context.LOCATION_SERVICE) as LocationManager
var location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER)
if (location == null) {
location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
}
val gpsLocationListener = object : LocationListener {
override fun onLocationChanged(p0: Location) {
location = p0
Log.d("LatLng", "Lat : ${location.latitude}, Lng : ${location.longitude}") // 위치는 잘만 받아옴..
}
override fun onStatusChanged(p0: String?, p1: Int, p2: Bundle?) {}
override fun onProviderEnabled(p0: String?) {}
override fun onProviderDisabled(p0: String?) {}
}
lm.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
sharedPreferences.getInt(SharedGroup.LOCATION_UPDATE_SECOND, 1)*1000L,
1f,
gpsLocationListener
)
lm.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
sharedPreferences.getInt(SharedGroup.LOCATION_UPDATE_SECOND, 1)*1000L,
1f,
gpsLocationListener
)
dbHelper = DBHelper(applicationContext, dbName, null, dbVersion)
var datas = dbHelper.getAllData()
receiver = MyReceiver()
for (data in datas) {
val filter = IntentFilter("my.app.Location.${data.id}")
registerReceiver(receiver, filter)
val intent = Intent("my.app.Location.${data.id}")
intent.putExtra("title", data.title)
intent.putExtra("lat", data.latitude)
intent.putExtra("lon", data.longtitude)
intent.putExtra("range", data.range)
val pending = PendingIntent.getBroadcast(applicationContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
lm.addProximityAlert(data.latitude, data.longtitude, data.range.toFloat(), -1, pending)
}
}
override fun onDestroy() {
super.onDestroy()
// lm.removeUpdates(this)
try {
unregisterReceiver(receiver)
} catch (e: IllegalArgumentException) {
e.printStackTrace()
}
}
@SuppressLint("MissingPermission")
override fun onRebind(intent: Intent?) {
super.onRebind(intent)
var location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER)
if (location == null) {
location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
}
// onLocationChanged(location)
// lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 1f, this)
}
}
Часть MyReceiver.kt
package my.app
import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationManager
import android.media.AudioManager
import android.os.Build
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
class MyReceiver : BroadcastReceiver() {
lateinit var mContext: Context
override fun onReceive(context: Context, intent: Intent) {
this.mContext = context
val sharedPreferences = context.getSharedPreferences("${context.packageName}_preferences", Context.MODE_PRIVATE)
var isValue = intent.getBooleanExtra(LocationManager.KEY_PROXIMITY_ENTERING, false)
var bundles = intent.extras
var keys = bundles!!.keySet()
for (key in keys) {
Log.d(TAG, "key=${key}, value=${bundles.get(key)}")
}
val nm = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(ChannelId.NOTIFY_ID, context.getString(R.string.volume_change_channel), NotificationManager.IMPORTANCE_DEFAULT)
nm.createNotificationChannel(channel)
}
val lm = mContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(mContext as Activity, Manifest.permission.ACCESS_FINE_LOCATION)) {
} else {
ActivityCompat.requestPermissions(mContext as Activity, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 0)
}
} else {
var location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER)
if (location == null)
location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
var loc1 = Location(""); var loc2 = Location("")
loc1.latitude = location.latitude; loc1.longitude = location.longitude
loc2.latitude = intent.getDoubleExtra("lat", 0.0); loc2.longitude = intent.getDoubleExtra("lon", 0.0)
var distance = loc1.distanceTo(loc2)
Log.d(TAG, "거리 : $distance, 범위 : ${intent.getDoubleExtra("range", 0.0)}" )
if (isValue) {
val noti = NotificationCompat.Builder(context, ChannelId.NOTIFY_ID)
noti.setContentTitle("title")
.setContentText("text")
.setSmallIcon(R.drawable.ic_icon)
.setShowWhen(true)
.setAutoCancel(true)
.setColor(ContextCompat.getColor(context, R.color.colorAccent))
.setDefaults(NotificationCompat.DEFAULT_ALL)
nm.notify(39186, noti.build())
// Toast.makeText(context, "목표 지점에 접근 중...", Toast.LENGTH_LONG).show()
Log.d(TAG, "목표 지점에 접근 중...")
} else {
val noti = NotificationCompat.Builder(context, ChannelId.NOTIFY_ID)
noti.setContentTitle("title")
.setSmallIcon(R.drawable.ic_icon)
.setShowWhen(true)
.setAutoCancel(true)
.setColor(ContextCompat.getColor(context, R.color.colorAccent))
.setDefaults(NotificationCompat.DEFAULT_ALL)
if (sharedPreferences.getBoolean(SharedGroup.VOLUME_OUT, true)) {
noti.setContentText(context.getString(R.string.location_out_content))
} else {
noti.setContentText(context.getString(R.string.left))
}
nm.notify(39186, noti.build())
Log.d(TAG, "목표 지점에서 벗어나는 중...")
}
}
}
}
Спасибо. Я не могу найти причину, по которой Proximity Alert не срабатывает. Я жду ваших ответов.