【问题标题】:android location - cannot get location in service when app is backgroundandroid位置-当应用程序为后台时无法在服务中获取位置
【发布时间】:2018-06-20 15:05:55
【问题描述】:

当应用程序处于后台时,我无法以间隔时间获取服务位置。服务工作并获取位置,但位置未更新,获取旧位置。我通过小米测试,也许miui有问题?我尝试了大约 5-10 种方式,但结果是一样的。打开应用时获取旧位置 获取新位置并关闭应用,获取具有旧纬度和经度的位置

例如第一种方式:

   locationManager = getApplicationContext().getSystemService(LOCATION_SERVICE) as LocationManager
    isGPSEnable = locationManager!!.isProviderEnabled(LocationManager.GPS_PROVIDER)
    isNetworkEnable = locationManager!!.isProviderEnabled(LocationManager.NETWORK_PROVIDER)

    if (!isGPSEnable && !isNetworkEnable) {

    } else {


        Log.e(TAG,"${isGPSEnable} ")
        if (isGPSEnable) {
            location = null
            locationManager!!.requestLocationUpdates(LocationManager.GPS_PROVIDER, LastKnownService.LOCATION_INTERVAL.toLong(), 0f, this)
            if (locationManager != null) {
                location = locationManager!!.getLastKnownLocation(LocationManager.GPS_PROVIDER)
                if (App.lastKnownLocation == null){

                    if (location != null) {
                        MLog.d(TAG,"${location!!.latitude}  ${location!!.longitude} == none")

                        App.lastKnownLocation = location



                        sendLocation(App.lastKnownLocation!!)



                        latitude = location!!.getLatitude()
                        longitude = location!!.getLongitude()
                        fn_update(location!!)
                    }


                }else{



                    if (location != null) {
                        MLog.d(TAG,"${location!!.latitude}  ${location!!.longitude} == ${location!!.distanceTo(App.lastKnownLocation)}")

                        App.lastKnownLocation = location




                        latitude = location!!.getLatitude()
                        longitude = location!!.getLongitude()
                        fn_update(location!!)


                            sendLocation(App.lastKnownLocation!!)

                    }

                }
            }
        }else if (isNetworkEnable) {
            location = null
            locationManager!!.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LastKnownService.LOCATION_INTERVAL.toLong(), 0f, this)
            if (locationManager != null) {
                location = locationManager!!.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
                if (App.lastKnownLocation == null){

                    if (location != null) {
                        MLog.d(TAG,"${location!!.latitude}  ${location!!.longitude} == none")

                        App.lastKnownLocation = location


                        sendLocation(App.lastKnownLocation!!)



                        latitude = location!!.getLatitude()
                        longitude = location!!.getLongitude()
                        fn_update(location!!)
                    }


                }else{



                    if (location != null) {

                        MLog.d(TAG,"${location!!.latitude}  ${location!!.longitude} == ${location!!.distanceTo(App.lastKnownLocation)}")

                        App.lastKnownLocation = location



                        latitude = location!!.getLatitude()
                        longitude = location!!.getLongitude()
                        fn_update(location!!)

                            sendLocation(App.lastKnownLocation!!)

                    }

                }
            }

        }

    }

第二种方式:

mLocationManager!!.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL.toLong(), LOCATION_DISTANCE,
                mLocationListeners[1])

 private var mLocationListeners = arrayOf(LocationListener(LocationManager.GPS_PROVIDER), LocationListener(LocationManager.NETWORK_PROVIDER))

private inner class LocationListener(provider: String) : android.location.LocationListener {
    internal var mLastLocation: Location

    init {
        Log.e(TAG, "LocationListener $provider")
        mLastLocation = Location(provider)
    }

    override fun onLocationChanged(location: Location) {
        Log.e(TAG, "onLocationChanged: $location")
        try{


            val mBuilder = NotificationCompat.Builder(this@LocationService, "123")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("location sended")
                    .setContentText("onlocation changed")
                    .setStyle(NotificationCompat.BigTextStyle()
                            .bigText("onlocation changed"))
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)

            if (notificationManager != null) notificationManager!!.notify(1,mBuilder.build())


                val distance = location.distanceTo(mLastLocation)

                if (distance > 10){
                    mLastLocation = location
                  sendLocation(mLastLocation)
                }











        }catch (e :java.lang.Exception){
            Log.e(TAG, "send http lat lon exception: $e")

        }

        mLastLocation.set(location)
    }

    override fun onProviderDisabled(provider: String) {
        Log.e(TAG, "onProviderDisabled: $provider")
    }

    override fun onProviderEnabled(provider: String) {
        Log.e(TAG, "onProviderEnabled: $provider")
    }

    override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {
        Log.e(TAG, "onStatusChanged: $provider")
    }
}

【问题讨论】:

  • 可能你的ui线程没有被后台线程更新?
  • @NiVeR 你能解释一下吗,因为现在我不知道明天我自己会觉得很糟糕,我应该为我们的客户介绍这个应用程序(
  • 您正在后台线程中更改位置。您如何通知 ui 线程有关此更改的信息?您需要提供一些代码
  • @NiVeR 我没有通知 ui 线程,我在服务中获取位置并向服务器请求

标签: android service location xiaomi miui


【解决方案1】:

您必须在电池优化中手动删除您的应用的电池优化限制(从安全应用转到电池选项并为您的应用选择无限制),然后它将起作用.. 但是如何以编程方式进行,我也是正在寻找那个..谢谢

【讨论】:

    【解决方案2】:

    调用这个方法:

    private fun openMiuiPowerKeeper(context: Context) {
        context.startActivity(Intent().apply {
            setClassName(
                "com.miui.powerkeeper",
                "com.miui.powerkeeper.ui.HiddenAppsConfigActivity"
            )
            putExtra("package_name", context.packageName)
            putExtra("package_label", context.getString(R.string.app_name))
            flags = Intent.FLAG_ACTIVITY_NEW_TASK
        })
    }
    

    它打开窗口,用户需要“不限制”行。你需要检查设备上的miui固件或其他东西,例如,像这样:

     private fun isFirmwareMiui(context: Context): Boolean {
        if (Build.MANUFACTURER.equals("xiaomi", true)) {
            context.packageManager.getInstalledPackages(PackageManager.GET_META_DATA).forEach {
                return it.packageName.startsWith("com.miui.")
            }
        }
        return false
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-14
      • 1970-01-01
      • 2015-09-05
      • 2014-07-23
      • 2011-09-05
      • 2013-05-06
      • 1970-01-01
      • 2021-07-06
      相关资源
      最近更新 更多