【问题标题】:Get datetime of LastKnownLocation获取 LastKnownLocation 的日期时间
【发布时间】:2021-11-28 04:33:05
【问题描述】:

我认为您可以使用 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 权限代码。如果你想要意味着我会在这里发布。

【问题讨论】:

    标签: android locationmanager android-gps


    【解决方案1】:

    是的,您可以获取,请尝试从位置对象获取时间,例如

    long time = location.gettime()
    
      public static String getDate(long milliSeconds, String dateFormat)
        {
            try {
                SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
                Calendar calendar = Calendar.getInstance();
                calendar.setTimeInMillis(milliSeconds);
                return formatter.format(calendar.getTime());
            }catch (Exception e){
                ExceptionHandler.printStackTrace(e);
            }
            return ""+milliSeconds;
        }
    
    
    getDate(time, "dd/MM/yy hh:mm:ss")
    

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-21
      • 2017-12-01
      • 2023-03-26
      相关资源
      最近更新 更多