【问题标题】:Get current location work as soon as access is allowed允许访问后立即获取当前位置工作
【发布时间】:2020-07-29 15:25:12
【问题描述】:

我已在我的应用程序中成功实现了谷歌地图和当前位置。我面临的唯一问题是,一旦用户接受了权限并允许定位,就需要重新加载片段,然后才能实现当前定位。

我的位置类:

public class LocationFragment extends Fragment implements OnMapReadyCallback {
    private LocationViewModel locationViewModel;
    private GoogleMap gMap;
    private MapView mapView;
    private Location currentLocation;
    private int LOCATION_PERMISSION_REQUEST_CODE = 1234;




    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        locationViewModel = ViewModelProviders.of( this ).get( LocationViewModel.class );
        View view = inflater.inflate( R.layout.fragment_location_customer, container, false );

        return view;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated( view, savedInstanceState );



        mapView = (MapView) view.findViewById( R.id.map );
        if (mapView != null)
        {
            mapView.onCreate( null );
            mapView.onResume();
            mapView.getMapAsync( this );

        }



    }

    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        UiSettings uiSettings = googleMap.getUiSettings();

        gMap = googleMap;
        LatLng coffeys = new LatLng( 54.572720, -5.959151 );
        gMap.addMarker( new MarkerOptions().position( coffeys ).title( "Coffey's Butchers" ) );
        gMap.moveCamera( CameraUpdateFactory.newLatLngZoom( coffeys, 12 ) );
        uiSettings.setZoomControlsEnabled(true);
        enableLocation();
    }





    public void enableLocation()
    {
        int permissionCheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);
        if (permissionCheck != PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
        }
        if(permissionCheck == PackageManager.PERMISSION_GRANTED)
        {
            gMap.setMyLocationEnabled( true );
            final LocationListener locationListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    // GPS may be turned off
                    if (location == null)
                    {
                        return;
                    }

                    Double lat = location.getLatitude();
                    Double lng = location.getLongitude();

                    currentLocation = location;
                    Toast.makeText( getActivity(), "Updated Location: " + lat + lng, Toast.LENGTH_SHORT ).show();

                }
            };

        }
    }

}

一旦允许访问,是否有办法让当前位置工作。

【问题讨论】:

标签: android location currentlocation


【解决方案1】:

使用requestPermissions() 而不是ActivityCompat.requestPermissions(),在您的片段中覆盖onRequestPermissionsResult(),并在获得权限的情况下运行依赖于该权限的代码。

检查这个问题:How to check permission in fragment

【讨论】:

    【解决方案2】:

    先决条件: EasyPermission 库


    第 1 步: 在清单文件中添加此权限

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    

    第 2 步:

        override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    
        //Create location callback when it's ready.
        createLocationCallback()
    
        //createing location request, how mant request would be requested.
        createLocationRequest()
    
        //Build check request location setting request
        buildLocationSettingsRequest()
        
        //FusedLocationApiClient which includes location 
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        //Location setting client
        mSettingsClient = LocationServices.getSettingsClient(this)
    
        //Check if you have ACCESS_FINE_LOCATION permission
        if (!EasyPermissions.hasPermissions(
                this@MainActivity,
                Manifest.permission.ACCESS_FINE_LOCATION)) {
            requestPermissionsRequired()
        }
        else{
            //If you have the permission we should check location is opened or not
            checkLocationIsTurnedOn()
        }
       
    }
    

    第 3 步: 创建需要在 onCreate()

    中调用的函数
    private fun requestPermissionsRequired() {
        EasyPermissions.requestPermissions(
            this,
            getString(R.string.location_is_required_msg),
            LOCATION_REQUEST,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
    }
    
    private fun createLocationCallback() {
        //Here the location will be updated, when we could access the location we got result on this callback.
        mLocationCallback = object : LocationCallback() {
            override fun onLocationResult(locationResult: LocationResult) {
                super.onLocationResult(locationResult)
                mCurrentLocation = locationResult.lastLocation
            }
        }
    }
    
    private fun buildLocationSettingsRequest() {
        val builder = LocationSettingsRequest.Builder()
        builder.addLocationRequest(mLocationRequest!!)
        mLocationSettingsRequest = builder.build()
        builder.setAlwaysShow(true)
    }
    
    private fun createLocationRequest() {
        mLocationRequest = LocationRequest.create()
        mLocationRequest!!.interval = 0
        mLocationRequest!!.fastestInterval = 0
        mLocationRequest!!.numUpdates = 1
        mLocationRequest!!.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    }
    
    public fun checkLocationIsTurnedOn() { // Begin by checking if the device has the necessary location settings.
        mSettingsClient!!.checkLocationSettings(mLocationSettingsRequest)
            .addOnSuccessListener(this) {
                Log.i(TAG, "All location settings are satisfied.")
                startLocationUpdates()
            }
            .addOnFailureListener(this) { e ->
                val statusCode = (e as ApiException).statusCode
                when (statusCode) {
                    LocationSettingsStatusCodes.RESOLUTION_REQUIRED -> {
                        try {
                            val rae = e as ResolvableApiException
                            rae.startResolutionForResult(this@MainActivity, LOCATION_IS_OPENED_CODE)
                        } catch (sie: IntentSender.SendIntentException) {
                        }
                    }
                    LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE -> {
                        mRequestingLocationUpdates = false
                    }
                }
            }
    }
    
    private fun startLocationUpdates() {
        mFusedLocationClient!!.requestLocationUpdates(
            mLocationRequest,
            mLocationCallback, null
        )
    }
    

    第 4 步:

    确保位置已打开或用户接受打开位置后,在 onActivityResult() 中处理回调。

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            LOCATION_IS_OPENED_CODE -> {
                if (resultCode == AppCompatActivity.RESULT_OK) {
                    Log.d(TAG, "Location result is OK")
                } else {
                    activity?.finish()
                }
            }
    }
    

    第 5 步: 从 FusedClientApi 获取最后一个已知位置

    override fun onMapReady(map: GoogleMap) {
        mMap = map
        mFusedLocationClient.lastLocation.addOnSuccessListener {
            if(it!=null){
                locateUserInMap(it)
            }
        }
    
    }
       private fun locateUserInMap(location: Location) {
        showLocationSafetyInformation()
        if(mMap!=null){
            val currentLocation = LatLng(location.latitude,location.longitude )
            addMarker(currentLocation)
        }
    }
    
    
    private fun addMarker(currentLocation: LatLng) {
        val cameraUpdate = CameraUpdateFactory.newLatLng(currentLocation)
        mMap?.clear()
        mMap?.addMarker(
            MarkerOptions().position(currentLocation)
                .title("Current Location")
        )
        mMap?.moveCamera(cameraUpdate)
        mMap?.animateCamera(cameraUpdate)
        mMap?.setMinZoomPreference(14.0f);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-12
      • 2013-03-15
      • 2022-10-18
      • 1970-01-01
      相关资源
      最近更新 更多