首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在android中获取当前位置的经纬度

如何在android中获取当前位置的经纬度
EN

Stack Overflow用户
提问于 2013-07-08 12:26:53
回答 5查看 293.5K关注 0票数 74

在我的应用程序中,我在应用程序打开时获取当前位置的纬度和经度,但在应用程序关闭时不获取。

我使用Service类来获取应用程序中的当前位置、纬度和经度。

请告诉我如何在应用程序关闭时获取当前位置的纬度和经度

EN

Stack Overflow用户

发布于 2021-11-29 20:26:03

对于这个漏洞,你可以使用流代码:

代码语言:javascript
运行
复制
public class GetLocationActivity extends BaseActivity {
//for getting update of location
FusedLocationProviderClient fusedLocationClient;
//new callback result requesting in activity
ActivityResultLauncher<String[]> locationPermissionRequest =
        registerForActivityResult(new ActivityResultContracts
                        .RequestMultiplePermissions(), result -> {
                    Boolean fineLocationGranted = result.get(
                            Manifest.permission.ACCESS_FINE_LOCATION);
                    Boolean coarseLocationGranted = result.get(
                            Manifest.permission.ACCESS_COARSE_LOCATION);
                    if (fineLocationGranted != null && fineLocationGranted) {
                        // Precise location access granted.
                        if (coarseLocationGranted != null && coarseLocationGranted) {
                            // Only approximate location access granted.
                            //chek is Gps is On or Off and ask from user to enable is
                            checkGPS();
                        }
                    } else {
                        // No location access granted.
                        //show toast for errors
                    }
                }
        );

private void checkGPS() {
//create call for checking gps sensor
    LocationRequest locationRequest = LocationRequest.create();

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);

    SettingsClient settingsClient = LocationServices.getSettingsClient(this);
    Task<LocationSettingsResponse> task = settingsClient.checkLocationSettings(builder.build());

    task.addOnSuccessListener(this, locationSettingsResponse -> {
        Log.d("GPS_main", "OnSuccess");
        // GPS is ON
    });

    task.addOnFailureListener(this, new OnFailureListener() {
        @Override
        public void onFailure(@NonNull final Exception e) {
            Log.d("GPS_main", "GPS off");
          
            // GPS off
            if (e instanceof ResolvableApiException) {
                ResolvableApiException resolvable = (ResolvableApiException) e;
                try {
                    resolvable.startResolutionForResult(GetLocationActivity.this, 1);
                } catch (IntentSender.SendIntentException e1) {
                    e1.printStackTrace();
                }
            }
        }
    });
}




@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
   
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    //location button
    findViewById(R.id.lastLocationFab).setOnClickListener(view -> getPermission());
   
}

private void getPermission() {
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        //call request
        locationPermissionRequest.launch(new String[]{
                Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION});

    } else {
        fusedLocationClient.requestLocationUpdates(LocationRequest.create()
                        .setInterval(36000).setFastestInterval(36000)
                        .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
                        .setMaxWaitTime(1000),
                getLocationCallback(), Looper.myLooper());
        getCurrentLocation();
    }
}

private LocationCallback getLocationCallback() {
    return new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            List<Location> locationList = locationResult.getLocations();
            if (locationList.size() > 0) {
                //The last location in the list is the newest
                Location location = locationList.get(locationList.size() - 1);

            
                //Place current location marker
              
            }
        }

        
    };
}


public void getCurrentLocation() {
    fusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY, new CancellationToken() {
        @Override
        public boolean isCancellationRequested() {
            return false;
        }

        @NonNull
        @Override
        public CancellationToken onCanceledRequested(@NonNull OnTokenCanceledListener onTokenCanceledListener) {
            return null;
        }
    }).addOnSuccessListener(this, location -> {
        // Got last known location. In some rare situations this can be null.
        if (location != null) {
            LatLng myLoc = new LatLng(location.getLatitude(), location.getLongitude());
           
        }
    });

  }
票数 0
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17519198

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档