You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取LastKnownLocation的日期时间?FusedLocationProviderClient实现方案

安卓获取LastKnownLocation对应日期时间的实现方案

安卓开发中如需获取LastKnownLocation对应的日期时间,可使用FusedLocationProviderClient替代LocationManager实现经纬度、日期及时间的获取,参考代码如下:

private FusedLocationProviderClient fusedLocationClient;
private Location lastKnownLocation;
private void getDeviceLocation() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        Task<Location> locationResult = fusedLocationClient.getLastLocation();
        locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
            @Override
            public void onComplete(@NonNull Task<Location> task) {
                if (task.isSuccessful()) {
                    // Set the map's camera position to the current location of the device.
                    lastKnownLocation = task.getResult();
                    if (lastKnownLocation != null) {
                        map.moveCamera(CameraUpdateFactory.newLatLngZoom(
                                new LatLng(lastKnownLocation.getLatitude(),
                                        lastKnownLocation.getLongitude()), DEFAULT_ZOOM));
                        long time = lastKnownLocation.getTime();
                        Date date = new Date(time);
                        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
                        String str=simpleDateFormat.format(date);
                        Toast.makeText(MapsActivity.this,"time: "+str,Toast.LENGTH_LONG).show();

                    }
                }
            }
        });
    }
  • 该代码实测运行正常,可直接参考使用
  • 代码中未包含GPS权限申请相关逻辑,如有需要可自行补充
  • 若代码存在错误欢迎指正

内容的提问来源于stack exchange,提问作者stackved12

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 14:36:04