본문 바로가기

안드로이드

android 타임아웃 주고 현재위치 찾기

implementation 'com.google.android.gms:play-services-location:21.0.0'

 

private FusedLocationProviderClient fusedLocationProviderClient;
boolean locationReceived=false;
Handler timeoutHandler;


private void getLocation() {
    timeoutHandler = new Handler();
    fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(IntroActivity.this);


    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        stopLocationUpdates();
        return;
    }


    Task<Location> locationTask = fusedLocationProviderClient.getCurrentLocation(PRIORITY_HIGH_ACCURACY, null);


    locationTask.addOnSuccessListener(location -> {
        if (location != null) {

            locationReceived = true;


            Log.d("myLog", "location.getLatitude() " + location.getLatitude());
            Log.d("myLog", "location.getLongitude() " + location.getLongitude());


        } else {


        }


        stopLocationUpdates();




    });


    locationTask.addOnFailureListener(e -> {


        stopLocationUpdates();
    });




    timeoutHandler.postDelayed(new Runnable() {
        @Override
        public void run() {
            if (!locationReceived) {


                stopLocationUpdates();
            }
        }
    }, 10000); // 10 seconds timeout






}



private void stopLocationUpdates() {
    timeoutHandler.removeCallbacksAndMessages(null);
    locationReceived = true;


}