前景服务在40到60秒后自动暂停
我正在使用位置跟踪应用程序。该应用程序在其他情况下运行良好,但是当它的工作前进时,只需几秒钟或一分钟。当我再次回到应用程序时,前景将再次起作用。
我缺少什么或以错误的方式实施该方法?
注意:我尝试了不同的方法,但仍然存在相同的问题。
- 实施警报
- 实施广播的
- 不同前景服务
- 等,
但我仍然觉得自己做错了什么;只需帮助我抓住这个问题并指导我
这是我的服务类:
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:
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)
}
}
谢谢您提前
I am working on location tracking app. this app is working fine in other conditions but when comes to foreground its work only for few seconds or a minute. When I again come back to app foreground will work again.
What am I missing or am I implementing the method in a wrong way?
Note: I have tried different approaches, but still have the same issue.
- implementing alarm
- implementing broadcast
- different way of foreground service
- etc
but I still feel somewhere I am doing something wrong; just help me to catch this and guide me
This is my service class:
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())
}
}
This is how I am calling the service in userActivity
class:
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
}
This is broadcastReceiver
class:
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)
}
}
Thank you in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在手机上,您可以在设置中打开它> autostart
On your phone, you can turn it on in settings>applications>autostart
this 链接说明如何即使不使用该应用程序,即使不使用该应用程序,link如何连续获取位置更新或屏幕关闭
This link explains how to get location updates continuously in the background even while not using the application OR screen is OFF