我正在开发位置跟踪应用程序。这个应用程序在其他条件下工作正常,但当进入前台时,它的工作时间只有几秒钟或一分钟。当我再次回到应用程序前台时将再次工作。
我遗漏了什么或者我以错误的方式实现该方法?
注意:我尝试了不同的方法,但仍然遇到同样的问题。
但我还是觉得自己哪里做错了;请帮助我抓住这个并指导我
这是我的服务类别:
class TestForegroundService : Service() {
lateinit var database: DatabaseReference
//region data
private val UPDATE_INTERVAL_IN_MILLISECONDS: Long = 3000
private var mFusedLocationClient: FusedLocationProviderClient? = null
private var locationRequest: LocationRequest? = null
private val locationSettingsRequest: LocationSettingsRequest? = null
companion object {
var isServiceRunning = false
const val ACTION_START_FOREGROUND_SERVICE = "ACTION_START_FOREGROUND_SERVICE"
const val ACTION_STOP_FOREGROUND_SERVICE = "ACTION_STOP_FOREGROUND_SERVICE"
const val NOTIFICATION_CHANNEL_ID = "YOUR_NOTIFICATION_CHANNEL_ID"
}
//sharing location
override fun onCreate() {
super.onCreate()
initData()
}
// sharing location
private val locationCallback: LocationCallback = object : LocationCallback() {
override fun onLocationResult(locationResult: LocationResult) {
super.onLocationResult(locationResult)
val currentLocation: Location = locationResult.lastLocation
Log.d(
"Locations",
currentLocation.getLatitude().toString() + "," + currentLocation.getLongitude()
)
//Share/Publish Location
}
}
private fun initData() {
locationRequest = LocationRequest.create();
locationRequest!!.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
locationRequest!!.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mFusedLocationClient =
LocationServices.getFusedLocationProviderClient(application)
}
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onTaskRemoved(rootIntent: Intent?) {
initAlarm()
super.onTaskRemoved(rootIntent)
}
private fun initAlarm() {
val alarmMgr = getSystemService(Context.ALARM_SERVICE) as AlarmManager
val intent = Intent(this, TestForegroundService::class.java)
val alarmIntent = PendingIntent.getBroadcast(this, 0, intent, 0)
alarmMgr[AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() +
2000] = alarmIntent
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
ACTION_START_FOREGROUND_SERVICE -> {
isServiceRunning = true
startForegroundService()
createNotificationChannel()
startLocationUpdates()
}
ACTION_STOP_FOREGROUND_SERVICE -> {
isServiceRunning = false
stopForeground(true)
createNotificationChannel()
stopSelf()
}
}
return START_STICKY
}
//inside service sharing location
private fun startLocationUpdates() {
// if (checkLocationPermission())
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return
}
mFusedLocationClient!!.requestLocationUpdates(
this.locationRequest!!,
this.locationCallback, Looper.myLooper()!!
)
}
private fun startForegroundService() {
val pendingIntent = Intent(this, UserActivity::class.java).let {
it.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
PendingIntent.getActivity(this, 0, it, 0)
}
val notification = NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
.setOngoing(true)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentIntent(pendingIntent)
.setContentTitle("TestForegroundService")
.setContentText("This is content text of notification")
.setChannelId(NOTIFICATION_CHANNEL_ID)
.build()
Toast.makeText(this, "${currentDAte()}", Toast.LENGTH_SHORT).show()
startForeground(1, notification)
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val serviceChannel = NotificationChannel(
NOTIFICATION_CHANNEL_ID,
"Test Service Channel",
NotificationManager.IMPORTANCE_DEFAULT
)
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(serviceChannel)
}
}
fun currentDAte(): String {
val sdfTime = SimpleDateFormat("HH:mm:ss")
return sdfTime.format(Date())
}
}
这就是我在
userActivity
类中调用服务的方式:
private fun shareLocation() {
isLocationSharing = true
val serviceIntent = Intent(this, TestForegroundService::class.java)
serviceIntent.action = TestForegroundService.ACTION_START_FOREGROUND_SERVICE
startService(serviceIntent)
// LocationServiceforground.startService(this, "service started")
Toast.makeText(this@UserActivity, "location enabled", Toast.LENGTH_SHORT).show()
location.visibility = View.GONE
beingTrack.visibility = View.VISIBLE
locationGif.visibility = View.VISIBLE
}
这是
broadcastReceiver
课程:
class MyReceiver: BroadcastReceiver() {
override fun onReceive(p0: Context?, intent: Intent) {
val serviceIntent = Intent(p0, TestForegroundService::class.java)
serviceIntent.action = TestForegroundService.ACTION_START_FOREGROUND_SERVICE
p0!!.startService(serviceIntent)
}
}
提前谢谢您