【问题标题】:forground service getting auto pause after 40 to 60 seconds前台服务在 40 到 60 秒后自动暂停
【发布时间】:2022-11-26 18:46:36
【问题描述】:

我正在开发位置跟踪应用程序。该应用程序在其他条件下运行良好,但在前台运行时仅持续几秒钟或一分钟。当我再次回到应用程序时,forground 将再次工作我在哪里失踪或者我以错误的方式实施该方法**注意:我尝试了不同的方式,但仍然是同样的问题**

  • 实施警报

  • 实施广播

  • 不同的前台服务方式

  • ETC *但我仍然觉得有些地方我做错了只是帮我抓住并引导我* 这是我的服务等级

    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)
    }
 }

**先感谢您 **

【问题讨论】:

    标签: android kotlin location background-service foreground-service


    【解决方案1】:

    在您的手机上,您可以在设置>应用程序>自动启动中打开它

    【讨论】:

    • 这是什么答案
    【解决方案2】:

    This 链接解释了如何在不使用应用程序或屏幕关闭时在后台持续获取位置更新

    【讨论】:

      猜你喜欢
      • 2019-05-11
      • 1970-01-01
      • 1970-01-01
      • 2011-07-22
      • 2013-02-03
      • 1970-01-01
      • 2018-01-11
      • 2018-07-31
      • 1970-01-01
      相关资源
      最近更新 更多