Fixed Location Permission issue on Android - 1
This commit is contained in:
@ -9,6 +9,7 @@
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />
|
||||
<application
|
||||
android:label="岐阜ナビ"
|
||||
android:name="${applicationName}"
|
||||
|
||||
@ -20,6 +20,7 @@ import com.google.android.gms.location.LocationCallback
|
||||
import com.google.android.gms.location.LocationRequest
|
||||
import com.google.android.gms.location.LocationResult
|
||||
import com.google.android.gms.location.LocationServices
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.GlobalScope
|
||||
import kotlinx.coroutines.launch
|
||||
import java.text.SimpleDateFormat
|
||||
@ -27,6 +28,7 @@ import java.util.Date
|
||||
import java.util.Locale
|
||||
import android.app.Notification
|
||||
|
||||
|
||||
data class GpsData(
|
||||
val id: Int,
|
||||
val team_name: String,
|
||||
@ -54,6 +56,7 @@ class GpsDatabaseHelper(private val context: Context) {
|
||||
|
||||
class LocationService : Service() {
|
||||
private lateinit var fusedLocationClient: FusedLocationProviderClient
|
||||
private lateinit var gpsDatabaseHelper: GpsDatabaseHelper
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? {
|
||||
return null
|
||||
@ -61,12 +64,13 @@ class LocationService : Service() {
|
||||
|
||||
override fun onCreate() {
|
||||
super.onCreate()
|
||||
Log.d("LocationService", "Android: onCreate.")
|
||||
|
||||
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
|
||||
gpsDatabaseHelper = GpsDatabaseHelper.getInstance(applicationContext)
|
||||
|
||||
// 位置情報の権限チェックとGPS有効化の確認を行う
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
|
||||
ContextCompat.checkSelfPermission(this, Manifest.permission.FOREGROUND_SERVICE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
|
||||
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
|
||||
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
|
||||
val locationRequest = LocationRequest.create().apply {
|
||||
@ -75,45 +79,37 @@ class LocationService : Service() {
|
||||
fastestInterval = 5000
|
||||
}
|
||||
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null)
|
||||
|
||||
// フォアグラウンドサービスの設定
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val channel = NotificationChannel(CHANNEL_ID, "Location", NotificationManager.IMPORTANCE_DEFAULT)
|
||||
val notificationManager = getSystemService(NotificationManager::class.java)
|
||||
notificationManager?.createNotificationChannel(channel)
|
||||
}
|
||||
val notification = NotificationCompat.Builder(this, CHANNEL_ID)
|
||||
.setContentTitle("Tracking location...")
|
||||
.setContentText("Location: null")
|
||||
.setSmallIcon(android.R.drawable.ic_menu_mylocation)
|
||||
.setOngoing(true)
|
||||
.build()
|
||||
|
||||
startForeground(NOTIFICATION_ID, notification)
|
||||
} else {
|
||||
Log.d("LocationService", "GPS is disabled.")
|
||||
// GPSが無効の場合の処理を追加する(例: ユーザーにGPSを有効にするように促すなど)
|
||||
stopSelf() // サービスを停止する
|
||||
}
|
||||
} else {
|
||||
Log.d("LocationService", "Location permission is not granted.")
|
||||
// 位置情報の権限が許可されていない場合の処理を追加する
|
||||
Log.d("LocationService", "Location permission or Foreground service location permission is not granted.")
|
||||
// 位置情報の権限またはフォアグラウンドサービスの位置情報の権限が許可されていない場合の処理を追加する
|
||||
stopSelf() // サービスを停止する
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
// GPSデバイスが有効になっているか確認する
|
||||
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
|
||||
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
|
||||
Log.d("LocationService", "GPS is disabled.")
|
||||
// GPSが無効の場合の処理を追加する(例: ユーザーにGPSを有効にするように促すなど)
|
||||
}else{
|
||||
Log.d("LocationService", "GPS is enabled.")
|
||||
}
|
||||
*/
|
||||
|
||||
// フォアグラウンドサービスの設定
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
val CHANNEL_ID = "location"
|
||||
val channel = NotificationChannel(CHANNEL_ID, "Location", NotificationManager.IMPORTANCE_DEFAULT)
|
||||
val notificationManager = getSystemService(NotificationManager::class.java) // この行を追加
|
||||
|
||||
Log.d("LocationService", "Android: Foreground service.")
|
||||
|
||||
notificationManager?.createNotificationChannel(channel)
|
||||
}
|
||||
val notification = NotificationCompat.Builder(this, "location")
|
||||
.setContentTitle("Tracking location...")
|
||||
.setContentText("Location: null")
|
||||
.setSmallIcon(android.R.drawable.ic_menu_mylocation) // リソースが存在しないため0を設定
|
||||
.setOngoing(true)
|
||||
.build()
|
||||
Log.d("LocationService", "Android: Foreground service 2.")
|
||||
|
||||
startForeground(1, notification)
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
return START_STICKY
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
@ -170,8 +166,6 @@ class LocationService : Service() {
|
||||
private val locationCallback = object : LocationCallback() {
|
||||
override fun onLocationResult(locationResult: LocationResult) {
|
||||
val currentLocation = locationResult.lastLocation
|
||||
//Log.d("LocationService", "Android: onLocationResult.")
|
||||
|
||||
if (currentLocation != null) {
|
||||
val accuracy = currentLocation.accuracy
|
||||
if (accuracy <= 30) {
|
||||
@ -181,13 +175,12 @@ class LocationService : Service() {
|
||||
val lon = currentLocation.longitude
|
||||
val currentTime = System.currentTimeMillis()
|
||||
|
||||
// GPS データをデバッグ用に表示
|
||||
// GPSデータをデバッグ用に表示
|
||||
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
|
||||
val formattedTime = sdf.format(Date(currentTime))
|
||||
//Log.d("LocationService", "Latitude: $lat, Longitude: $lon, Time: $formattedTime, Accuracy: $accuracy")
|
||||
|
||||
// GPS データをデータベースに保存
|
||||
GlobalScope.launch {
|
||||
// GPSデータをデータベースに保存
|
||||
GlobalScope.launch(Dispatchers.IO) {
|
||||
addGPStoDB(lat, lon, currentTime)
|
||||
}
|
||||
|
||||
@ -203,36 +196,16 @@ class LocationService : Service() {
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
Log.d("LocationService", "Android: onStartCommand.")
|
||||
|
||||
/* onCreate でやってるので除外。
|
||||
// 位置情報の権限チェックとGPS有効化の確認を行う
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
|
||||
val locationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
|
||||
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
|
||||
val locationRequest = LocationRequest.create().apply {
|
||||
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
|
||||
interval = 10000
|
||||
fastestInterval = 5000
|
||||
}
|
||||
fusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, null)
|
||||
} else {
|
||||
Log.d("LocationService", "GPS is disabled.")
|
||||
// GPSが無効の場合の処理を追加する(例: ユーザーにGPSを有効にするように促すなど)
|
||||
}
|
||||
} else {
|
||||
Log.d("LocationService", "Location permission is not granted.")
|
||||
// 位置情報の権限が許可されていない場合の処理を追加する
|
||||
}
|
||||
|
||||
*/
|
||||
|
||||
// Foregroundサービスを開始
|
||||
startForeground(NOTIFICATION_ID, createNotification())
|
||||
|
||||
return START_STICKY
|
||||
}
|
||||
*/
|
||||
|
||||
private suspend fun addGPStoDB(lat: Double, lng: Double, timestamp: Long, isCheckin: Int = 0) {
|
||||
try {
|
||||
@ -241,7 +214,6 @@ class LocationService : Service() {
|
||||
val teamName = preferences.getString("team_name", "") ?: ""
|
||||
val eventCode = preferences.getString("event_code", "") ?: ""
|
||||
|
||||
|
||||
if (teamName.isNotEmpty() && eventCode.isNotEmpty()) {
|
||||
val gpsData = GpsData(
|
||||
id = 0,
|
||||
@ -253,13 +225,12 @@ class LocationService : Service() {
|
||||
created_at = timestamp
|
||||
)
|
||||
|
||||
val db = GpsDatabaseHelper.getInstance(context)
|
||||
db.insertGps(gpsData)
|
||||
gpsDatabaseHelper.insertGps(gpsData)
|
||||
Log.d("LocationService", "Android: addGPStoDB.")
|
||||
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.e("LocationService", "Error adding GPS data to DB", e)
|
||||
// エラーメッセージをユーザーに表示するなどの処理を追加
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -36,6 +36,11 @@ class MainActivity: FlutterActivity() {
|
||||
stopLocationService()
|
||||
result.success(null)
|
||||
}
|
||||
"isLocationServiceRunning" -> {
|
||||
Log.d("MainActivity", "Android: called isLocationServiceRunnung.")
|
||||
val isRunning = isServiceRunning(LocationService::class.java)
|
||||
result.success(isRunning)
|
||||
}
|
||||
else -> {
|
||||
result.notImplemented()
|
||||
}
|
||||
@ -75,9 +80,8 @@ class MainActivity: FlutterActivity() {
|
||||
}
|
||||
|
||||
private fun startLocationService() {
|
||||
Log.d("MainActivity", "Android: startLocationService.")
|
||||
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
|
||||
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
|
||||
ContextCompat.checkSelfPermission(this, Manifest.permission.FOREGROUND_SERVICE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
|
||||
if (!isServiceRunning(LocationService::class.java)) {
|
||||
val intent = Intent(this, LocationService::class.java)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
@ -91,16 +95,19 @@ class MainActivity: FlutterActivity() {
|
||||
Log.d("MainActivity", "Location service is already running.")
|
||||
}
|
||||
} else {
|
||||
Log.d("MainActivity", "Location permission is not granted.")
|
||||
// 位置情報の権限が許可されていない場合の処理を追加する
|
||||
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), PERMISSION_REQUEST_CODE)
|
||||
Log.d("MainActivity", "Location permission or Foreground service location permission is not granted.")
|
||||
// 位置情報の権限またはフォアグラウンドサービスの位置情報の権限が許可されていない場合の処理を追加する
|
||||
// 例: ユーザーに権限の必要性を説明し、許可を求めるダイアログを表示するなど
|
||||
}
|
||||
}
|
||||
|
||||
private fun stopLocationService() {
|
||||
Log.d("MainActivity", "Android: stopLocationService.")
|
||||
val intent = Intent(this, LocationService::class.java)
|
||||
stopService(intent)
|
||||
if (isServiceRunning(LocationService::class.java)) {
|
||||
val intent = Intent(this, LocationService::class.java)
|
||||
stopService(intent)
|
||||
} else {
|
||||
Log.d("MainActivity", "Location service is not running.")
|
||||
}
|
||||
}
|
||||
|
||||
private fun isServiceRunning(serviceClass: Class<*>): Boolean {
|
||||
|
||||
Reference in New Issue
Block a user