前景服务在40到60秒后自动暂停

发布于 2025-01-21 16:22:51 字数 6440 浏览 0 评论 0原文

我正在使用位置跟踪应用程序。该应用程序在其他情况下运行良好,但是当它的工作前进时,只需几秒钟或一分钟。当我再次回到应用程序时,前景将再次起作用。

我缺少什么或以错误的方式实施该方法?

注意:我尝试了不同的方法,但仍然存在相同的问题。

  • 实施警报
  • 实施广播的
  • 不同前景服务
  • 等,

但我仍然觉得自己做错了什么;只需帮助我抓住这个问题并指导我

这是我的服务类:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

メ斷腸人バ 2025-01-28 16:22:51

在手机上,您可以在设置中打开它> autostart

On your phone, you can turn it on in settings>applications>autostart

没有心的人 2025-01-28 16:22:51

this 链接说明如何即使不使用该应用程序,即使不使用该应用程序,link如何连续获取位置更新或屏幕关闭

This link explains how to get location updates continuously in the background even while not using the application OR screen is OFF

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文