android–FusedLocationProviderClient始终为null,locationAvailability通常为false

android–FusedLocationProviderClient始终为null,locationAvailability通常为false,第1张

概述我正在使用jobScheduler来获取后台位置更新.但每次调度作业时,FusedLocationProviderClient都为null.这是为什么?我检查了(FusedLocationProviderClient==null)条件,并且每次调度作业时,其下的代码都会运行(这意味着fusionLocationProviderClient在初始化后为null.)请查看下面的代

我正在使用jobScheduler来获取后台位置更新.但每次调度作业时,FusedLocationProvIDerClIEnt都为null.这是为什么?我检查了(FusedLocationProvIDerClIEnt == null)条件,并且每次调度作业时,其下的代码都会运行(这意味着fusionLocationProvIDerClIEnt在初始化后为null.)请查看下面的代码.此外,locationAvailability通常为false,因此不会调用onLocationResult来提供null位置值.如何优化FusedLocationProvIDerClIEnt.还有一件事,fuseLocationProvIDerClIEnt是否始终为null,而locationAvailability是否为false相关?

@OverrIDepublic boolean onStartJob(JobParameters jobParameters) {    Log.e("onStartJob", "onStartJob");//for deBUG    jobP = jobParameters;    if (!checkAndRequestPermissions()) {        Toast.makeText(this, "Please provIDe location permission for paramount app.", Toast.LENGTH_LONG).show();        provIDer = null;    } else {        if (ActivityCompat.checkSelfPermission(this, androID.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&                ActivityCompat.checkSelfPermission(this, androID.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {        }        if (mLocationRequest == null) {            Log.e("onStartJob", "LocationRequest initialized"); //for deBUG            mLocationRequest = LocationRequest.create();            mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);            mLocationRequest.setInterval(100 * 1000);            mLocationRequest.setFastestInterval(60 * 1000);        }        if (clIEnt == null) {            Log.e("onStartJob", "clIEnt initialized"); //for deBUG            clIEnt = LocationServices.getFusedLocationProvIDerClIEnt(this);            clIEnt.requestLocationUpdates(mLocationRequest, new LocationCallback() {                @OverrIDe                public voID onLocationResult(LocationResult locationResult) {                    Log.e("onLocationResult ", "onLocationResult");                    onLocationChanged(locationResult.getLastLocation());                }                @OverrIDe                public voID onLocationAvailability(LocationAvailability locationAvailability) {                    Log.e("onLocationAvailability", locationAvailability + "");;                }            },            Looper.myLooper());        }        try {            provIDer = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE) + "";            gpsProvIDer = provIDer;        } catch (Settings.SettingNotFoundException e) {            Log.e("provIDer", "gps provIDer error");        }    }    return true;}@OverrIDepublic boolean onStopJob(JobParameters jobParameters) {    Log.e("onStopJob", "onStopJob");//for deBUG    if (ul != null) {        ul.cancel(true);    }    return true;}public voID onLocationChanged(Location location) {    latitude = location.getLatitude() + "";    longitude = location.getLongitude() + "";    Log.e("latitude" , latitude);}

上面代码中的日志值如下所示:

03-15 17:09:25.889 10687-10687/com.myProject.com.jobschedulers E/onStartJob: onStartJob03-15 17:09:25.900 10687-10687/com.myProject.com.jobschedulers E/onstartJob: clIEnt initialized03-15 17:09:25.957 10687-10687/com.myProject.com.jobschedulers E/onLocationResult: onLocationResult03-15 17:09:25.960 10687-10687/com.myProject.com.jobschedulers E/onLocationAvailability: LocationAvailability[isLocationAvailable: true]03-15 17:23:26.975 10687-10687/com.myProject.com.jobschedulers E/onStartJob: onStartJob03-15 17:23:26.993 10687-10687/com.myProject.com.jobschedulers E/onstartJob: clIEnt initialized03-15 17:23:27.017 10687-10687/com.myProject.com.jobschedulers E/onLocationAvailability: LocationAvailability[isLocationAvailable: false]03-15 17:41:32.672 10687-10687/com.myProject.com.jobschedulers E/onStartJob: onStartJob03-15 17:41:32.690 10687-10687/com.myProject.com.jobschedulers E/onstartJob: clIEnt initialized03-15 17:41:32.741 10687-10687/com.myProject.com.jobschedulers E/onLocationAvailability: LocationAvailability[isLocationAvailable: false]03-15 17:53:17.335 10687-10687/com.myProject.com.jobschedulers E/onStartJob: onStartJob03-15 17:53:17.351 10687-10687/com.myProject.com.jobschedulers E/onstartJob: clIEnt initialized03-15 17:53:17.383 10687-10687/com.myProject.com.jobschedulers E/onLocationAvailability: LocationAvailability[isLocationAvailable: false]

解决方法:

JobScheduler仅来自21 API,考虑使用从PendingIntent从broadcastReceiver启动的JobIntentService,并从FusedLocationProvIDerClIEnt.requestLocationUpdates方法开始.
它看起来像这样:

class MainActivity : Activity() {    ...    lateinit var  mFusedLocationClIEnt:FusedLocationProvIDerClIEnt    lateinit var mLocationRequestBackground: LocationRequest    fun init {        mFusedLocationClIEnt = LocationServices.getFusedLocationProvIDerClIEnt(activity = this)        mLocationRequestBackground = LocationRequest()        mLocationRequestBackground.interval = UPDATE_INTERVAL_IN_MILliSECONDS_BACKGROUND // i.e. 15 minutes - you hope to get updates at this interval, in background it will be not more than few times per hour on AndroID Oreo        mLocationRequestBackground.fastestInterval = FASTEST_UPDATE_INTERVAL_IN_MILliSECONDS_BACKGROUND //i.e. 1 minute - updates will not come faster than this        mLocationRequestBackground.priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY //do not overwhelm user's device with requests, but use requests from other apps        mLocationRequestBackground.smallestdisplacement = 25f //distance in meters to trigger update    }    ...    fun onStop() {        //start updating in background        mFusedLocationClIEnt.requestLocationUpdates(mLocationRequestBackground,                    LocationbroadcastReceiver.getPendingIntent(activity = this))    }    ...}class LocationbroadcastReceiver : broadcastReceiver() {    companion object {        const val EXTRA_LATITUDE = "EXTRA_LATITUDE"        const val EXTRA_LONGITUDE = "EXTRA_LONGITUDE"        const val WAKEUP = "com.appID.intent.action.WAKEUP"        fun getPendingIntent(context: Context, userID: String? = null): PendingIntent {            val alarmIntent = Intent(context, LocationbroadcastReceiver::class.java)            alarmIntent.action = WAKEUP            return PendingIntent.getbroadcast(context, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT)        }    }    overrIDe fun onReceive(context: Context?, intent: Intent?) {        context ?: return        if (intent?.action != WAKEUP) return        val location: LocationResult? = LocationResult.extractResult(intent)        val loc: Location? = location?.lastLocation        loc?.apply {                val i = Intent(context, SendLocationService::class.java)                i.putExtra(EXTRA_LATITUDE, latitude)                i.putExtra(EXTRA_LONGITUDE, longitude)                SendLocationService.enqueueWork(context, i)        }    }}class SendLocationService : JobIntentService() {    companion object {        private const val JOB_ID = 1000        const val TAG = "SendLocationService"        fun enqueueWork(context: Context, work: Intent) {            enqueueWork(context, SendLocationService::class.java, JOB_ID, work)        }    }    private var sending: Boolean = false    overrIDe fun onHandleWork(intent: Intent) = runBlocking {        val latitude = intent.getDoubleExtra(LocationbroadcastReceiver.EXTRA_LATITUDE, 0.0)        val longitude = intent.getDoubleExtra(LocationbroadcastReceiver.EXTRA_LONGITUDE, 0.0)        suspendCoroutine<Unit> { continuation ->            YourAPI.postMyLocation(lat = latitude, lng = longitude)                    .callback { continuation.resume(Unit) }        }    }    overrIDe fun onStopCurrentWork(): Boolean {        return !sending    }}

不要忘记将它们添加到清单中

    <service androID:name=".services.SendLocationService"        androID:exported="false"        androID:permission="androID.permission.BIND_JOB_SERVICE"/>    <receiver androID:name=".services.LocationbroadcastReceiver"        androID:exported="false"/>
总结

以上是内存溢出为你收集整理的android – FusedLocationProviderClient始终为null,locationAvailability通常为false全部内容,希望文章能够帮你解决android – FusedLocationProviderClient始终为null,locationAvailability通常为false所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1116726.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-29
下一篇 2022-05-29

发表评论

登录后才能评论

评论列表(0条)

保存