0

For getting Location in JobScheduler, I need to get Activity Context for calling ActivityCompat.requestPermissions in onStartJob.

ActivityCompat.requestPermissions({}, permissions, REQUEST_CODE);

But I can't pass Activity Context to JobScheduler.

  class GetLocationJob : JobService() {

    override fun onStopJob(params: JobParameters?): Boolean {
        ...
    }

    override fun onStartJob(params: JobParameters?): Boolean {
        
      // Check Permission
      if (ActivityCompat.checkSelfPermission(
          this,
          Manifest.permission.ACCESS_FINE_LOCATION
        ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
          this,
          Manifest.permission.ACCESS_COARSE_LOCATION
        ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
          this,
          Manifest.permission.ACCESS_BACKGROUND_LOCATION
        ) != PackageManager.PERMISSION_GRANTED
      ) {
        val permissions = arrayOf(
          Manifest.permission.ACCESS_COARSE_LOCATION,
          Manifest.permission.ACCESS_FINE_LOCATION,
          Manifest.permission.ACCESS_BACKGROUND_LOCATION
        )

        // can't pass activity context 
        ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE);
      }
    

    // 2. create client
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

    // 3. get location
    fusedLocationClient.lastLocation
      .addOnSuccessListener { location: Location? ->
        println(location)
        if (location != null) {
          println(location.latitude)
        }
        if (location != null) {
          println(location.longitude)
        }
      }

    ...


    }
  }

y-tomimoto
  • 13
  • 2
  • not sure if it is fair to mark this as a duplicate, but [this might be related](https://stackoverflow.com/questions/45145990/pass-context-to-jobservice-android-jobscheduler) – a_local_nobody Nov 10 '20 at 12:50
  • 2
    other than that, move your permission checks out of the job, you're doing this when the job starts so maybe you can move these for before it begins ? – a_local_nobody Nov 10 '20 at 12:52
  • 2
    Agreed. You should be requesting permission before scheduling the job. If the job detects that it does not have permission, it can raise a `Notification` alerting the user to the problem, then shut down. – CommonsWare Nov 10 '20 at 12:57
  • Thanks, separated `ActivityCompat.requestPermissions` was working !! – y-tomimoto Nov 11 '20 at 10:59

0 Answers0