当前位置: 首页 > 知识库问答 >
问题:

手机重启后Android get位置为空

和和煦
2023-03-14

在我的应用程序中,我通过此功能获取手机的位置,但当我重新启动手机并启动应用程序时,我通过此方法获取空值。我有什么遗漏或做错的吗?我应该如何解决此问题?

下面是我使用的函数:

public void getAddress() {
        Log.v("--", "get address 1");
        boolean isGPSProviderEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network_enabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        Log.v("--", "get address 31 " + isGPSProviderEnabled + " gps  -  "
                + isConnectedToNetwork());

        if (isGPSProviderEnabled || network_enabled) {
            Log.v("--", "get address 2");
            Criteria c = new Criteria();
            Log.v("--", "provider " + locationManager.getBestProvider(c, true));
            locationManager.requestSingleUpdate(
                    locationManager.getBestProvider(c, true),
                    mLocationListener, Looper.myLooper());
            location = locationManager.getLastKnownLocation(locationManager
                    .getBestProvider(c, true));
            if (location == null) {
                Log.v("--", "get address 6");
                // TODO check if this is working
                locationManager.requestSingleUpdate(
                        locationManager.getBestProvider(c, true),
                        mLocationListener, Looper.myLooper());
                locationManager.requestLocationUpdates(
                        locationManager.getBestProvider(c, true), 0, 0,
                        mLocationListener);
                Location oldLocation = new Location("");
                oldLocation.setLatitude(new Double(prefs.getString(
                        Constants.LATITUDE, "48.51")));
                oldLocation.setLongitude(new Double(prefs.getString(
                        Constants.LONGITUDE, "2.20")));
                populateList(oldLocation);
                // locationManager.requestLocationUpdates(
                // locationManager.getBestProvider(c, true), 1000, 100,
                // mLocationListener);
            } else {
                Log.v("--", "get address 3");
                if (isConnectedToNetwork()) {
                    new AsyncTask<Void, Void, Void>() {
                        protected Void doInBackground(Void... params) {
                            try {
                                com.quanticapps.athan.utils.Geocoder geocoder = new com.quanticapps.athan.utils.Geocoder(
                                        Main.this);
                                GeocoderModel geocoderModel = geocoder
                                        .getFromLocation(
                                                location.getLatitude(),
                                                location.getLongitude(), 5);
                                city = geocoderModel.getCity();
                                country = geocoderModel.getCountry();
                                prefs.edit().putString(Constants.CITY, city)
                                        .apply();
                                Log.v("--", "get address 4");
                            } catch (IOException e) {
                                Log.v("--", "get address 11");
                                e.printStackTrace();
                            } catch (LimitExceededException e) {
                                Log.v("--", "get address 12");
                                e.printStackTrace();
                            }
                            return null;
                        };

                        protected void onPostExecute(Void result) {
                            prefs.edit().putString(Constants.COUNTRY, country)
                                    .apply();
                            prefs.edit().putString(Constants.CITY, city)
                                    .apply();
                            populateList(location);
                        };
                    }.execute();
                } else {
                    city = null;
                    Log.v("--", "get address 33 " + location.getLatitude());
                    populateList(location);
                }
            }
        } else {
            Log.v("--", "get address 5");
            startGpsEnableDialog();
        }

    }

和我的位置侦听器:

private final LocationListener mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(final Location location) {
            // TODO
            Log.v("--", "get address 121");
            if (location != null) {
                Main.this.location = location;
                getAddress();
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
            Log.v("--", "provider enabled");
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
            Log.v("--", "provider disabled");
        }
    };

共有2个答案

宫晟
2023-03-14

如果fusedLocationClient返回空位置,则应使用requestLocationUpdates

    fusedLocationClient.lastLocation
        .addOnSuccessListener { location: Location? ->
            if (location == null) {
                checkLocationSettingsAndStartLocationUpdates(
                    resolutionForResult
                )
            } else {
                showUserCurrentLocation(location)
            }
        }

首先,让我们定义resolutionForResult

private val resolutionForResult =
    registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { activityResult ->
        if (activityResult.resultCode == RESULT_OK)
            locationManger.startLocationUpdates(requestPermissionLauncher)
        else {
            showMessage("we can't determine your location")
        }
    }

那么这个方法

private fun checkLocationSettingsAndStartLocationUpdates(
    resolutionForResult: ActivityResultLauncher<IntentSenderRequest>
) {
    val builder = LocationSettingsRequest.Builder()
        .addLocationRequest(locationRequest)
    val client: SettingsClient = LocationServices.getSettingsClient(requireContext)
    val task: Task<LocationSettingsResponse> = client.checkLocationSettings(builder.build())

    task.addOnSuccessListener { _ ->
        startLocationUpdates()
    }

    task.addOnFailureListener { exception ->
        if (exception is ResolvableApiException) {
            // Location settings are not satisfied, but this can be fixed
            // by showing the user a dialog.
            try {
                val intentSenderRequest =
                    IntentSenderRequest.Builder(exception.resolution).build()
                resolutionForResult.launch(intentSenderRequest)
            } catch (sendEx: IntentSender.SendIntentException) {
            }
        }
    }
}

然后startLocationUpdates实际位置更新发生的位置

fun startLocationUpdates(
    ) {
        if (ActivityCompat.checkSelfPermission(
                requireContext,
                Manifest.permission.ACCESS_FINE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
                requireContext,
                Manifest.permission.ACCESS_COARSE_LOCATION
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            requestPermissionLauncher.launch(
                Manifest.permission.ACCESS_FINE_LOCATION
            )
            return
        }
        fusedLocationClient.requestLocationUpdates(
            locationRequest,
            locationCallback,
            Looper.getMainLooper()
        )
    }

这里还有locationRequestlocationCallback

private val locationRequest: LocationRequest by lazy {
    LocationRequest.create().apply {
        interval = 10000
        fastestInterval = 5000
        priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    }
}

private var locationCallback: LocationCallback = object : LocationCallback() {
    override fun onLocationResult(locationResult: LocationResult?) {
        locationResult ?: return
        for (location in locationResult.locations) {
            if (location != null) {
                //showUserCurrentLocation(location)
                stopLocationUpdates(this)//if you only need the location once then stop the updates
                break
            }
        }
    }
}

以下是stopLocationUpdates方法

fun stopLocationUpdates(locationCallback: LocationCallback) {
    fusedLocationClient.removeLocationUpdates(locationCallback)
}

此外,fusedLocationClient在用户授予权限或检查权限后定义,

以下是如何检查许可是否得到保证

fun locationPermissionGranted(): Boolean {
    return when (PackageManager.PERMISSION_GRANTED) {
        ContextCompat.checkSelfPermission(
            requireContext,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) -> {
            fusedLocationClient =
                LocationServices.getFusedLocationProviderClient(requireContext)
            true
        }
        else -> {
            false
        }
    }
}

如果是假的话,你需要申请许可证

 requestPermission(requestPermissionLauncher: ActivityResultLauncher<String>) {
        requestPermissionLauncher.launch(
            Manifest.permission.ACCESS_FINE_LOCATION
        )
    }

这里是的定义请求PermissionLauncher

private val requestPermissionLauncher = registerForActivityResult(
    ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
    if (isGranted) {
        fusedLocationClient =
                LocationServices.getFusedLocationProviderClient(requireContext())
    } else {
        showMessage(
            "the application can't show your " +
                    "current location on the map, because you denied the location permission"
        )
    }
}
庞修贤
2023-03-14

当手机重新启动时,缓存的最后一个位置将丢失,因此如果您没有打开使用GPS的应用程序(如谷歌地图或其他),则不会有最后一个位置。

永远不必返回给您一个位置,您应该始终假定它可以为null

 类似资料:
  • 我正在开发一个集成了提醒功能的Android应用程序。如果手机一直开着,通知就会起作用,但当我关机或重启时,我就失去了所有的警报。我知道这是和Android的功能来提高手机的效率,但我不知道该怎么办,我该怎么解决这个问题呢? 这里是我的文件: > AlarmService.java 下面是代码: AlarmService.java } 我该怎么办?

  • 我试图在摄像机前创建一个节点。 然而,当我先旋转手机(例如沿Y轴旋转90°),然后在位置(Cameron aPosition. x,Cameron aPosition. y,Cameron aPosition. z-远程节点)上创建节点时,它会在相机的旧位置前面创建节点,就好像手机没有旋转。 据我所知,坐标系没有随着手机移动。如何让前面要创建的节点成为摄像机的新位置? 非常感谢你!

  • 我目前正在开发一个Android应用程序,它使用Firebase消息来接收来自服务器的通知。 当应用程序强制关闭时,logcat中也会收到相同的消息。 我可以请求用户不要强制停止,但我如何阻止他们重新启动他们的设备。因此,在此背景下,我请求stackoverflow社区的帮助。我有什么办法可以知道应用程序在关闭时错过了一些消息吗?

  • 我正在构建一个通知应用程序,它使用警报管理器设置多个通知来提醒用户的日常任务,当手机打开一切都很好,但当重新启动手机时,通知会出现,但通知数据会丢失(例如通知内容),这些数据从我的第一个活动中保存到意图中,这是下面的代码。( 我的推送通知接收器

  • 问题内容: 有谁知道是否有可能获得有关设备范围内所有蜂窝塔的信息?只是能够获得它们的位置或有关它们的任何其他信息,以及我将如何去做? 问题答案: 这是从当前网络状态获取基站信号塔ID(CID)和lac(位置区号)的方法: 之后获取Lat,Lng位置信息比较麻烦。这是指向有关Symbian的帖子的链接,但涉及到Cell Tower-> Lat,Lng转换:http ://discussion.for

  • 问题内容: 关于基本的Android编程,我还有另一个问题: 如何访问GPS以获取正在运行该应用程序的手机的当前位置?检索信息需要多长时间?在这种情况下,GPS可能会被禁用,如何再次启用/禁用它。 必须在andorid清单中授予哪些权限? 问候和感谢您的回答, 诗丹 问题答案: 一些答案: 访问:请参见LocationManager和LocationListener。 权限:android.per