当应用程序具有服务后台时如何获取用户位置?

时间:2018-06-20 13:16:13

标签: android service

您好,我正在开发一个应用程序,该应用程序在后台获取用户位置并将其发送到Firebase数据库。当应用程序位于前台时,一切正常,但是当我将应用程序移至后台位置时,它没有刷新,它尝试获取位置,但始终提供相同的位置。 这是我的代码:

    private void fn_getlocation() {
    locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
    isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    if (!isGPSEnable && !isNetworkEnable) {

    } else {

        if (isNetworkEnable) {
            location = null;
            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;
            }
            else
            {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
                if (locationManager!=null){
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location!=null){

                        Log.e("latitude",location.getLatitude()+"");
                        Log.e("longitude",location.getLongitude()+"");

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

        }else if (isGPSEnable){
            location = null;
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
            if (locationManager!=null){
                location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location!=null){
                    Log.e("latitude",location.getLatitude()+"");
                    Log.e("longitude",location.getLongitude()+"");
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                    fn_update(location);
                }
            }
        }


    }

}

1 个答案:

答案 0 :(得分:0)

好的,我找到了解决方案。 Android Oreo中有一个用于优化电池的选项。此选项试图停止应用程序的后台任务。因此,您需要转到应用信息>电池>电池优化>取消选中您的应用