Android:是不是有任何解决方案可以每次使用 GPS 或网络获取准确位置 [重复]

Posted

技术标签:

【中文标题】Android:是不是有任何解决方案可以每次使用 GPS 或网络获取准确位置 [重复]【英文标题】:Android: Is there any solution for get accurate location everytime using GPS or Network [duplicate]Android:是否有任何解决方案可以每次使用 GPS 或网络获取准确位置 [重复] 【发布时间】:2018-08-06 17:16:00 【问题描述】:

我正在创建一个跟踪 android 应用程序,我正在使用 Fused locaiton api 获取位置,但有时会返回错误的位置。

请帮助每次获得准确的纬度。

下面的代码我用于获取 lat lang。代码运行良好,但有时它给出了磨损的位置。但是当我在我的设备中打开谷歌地图时,位置再次返回正确。

    @Override
    public void onConnected(Bundle bundle) 

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) 
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        
    

    @Override
    public void onConnectionSuspended(int i) 

    

    @Override
    public void onLocationChanged(Location location) 

        mLastLocation = location;
        currentLatitude = mLastLocation.getLatitude();
        currentLongitude = mLastLocation.getLongitude();

        currentLocation = new Location("");
        currentLocation.setLatitude(currentLatitude);
        currentLocation.setLongitude(currentLongitude);

        distanceInMeters = addressLocation.distanceTo(currentLocation);

        tvDistance.setText(String.valueOf(distanceInMeters) + " Mtr");

        if (distanceInMeters > GPS_RADIUS) 
            distanceStatus = "Not Matched";
            tvMatchStatus.setText(R.string.not_match);
            layout.setBackgroundColor(Color.parseColor("#FFFF0900"));
         else 
            distanceStatus = "Matched";
            tvMatchStatus.setText(R.string.matched);
            layout.setBackgroundColor(Color.parseColor("#FF2CFD03"));
        

        if (mCurrLocationMarker != null) 
            mCurrLocationMarker.remove();
        
        hideProgressDialogLocationMatch();
    

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) 
    

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String permissions[],
                                           @NonNull int[] grantResults) 
        switch (requestCode) 
            case MY_PERMISSIONS_REQUEST_LOCATION: 
                try 
                    // If request is cancelled, the result arrays are empty.
                    if (grantResults.length > 0
                            && grantResults[0] == PackageManager.PERMISSION_GRANTED) 

                        // permission was granted. Do the
                        // contacts-related task you need to do.
                        if (ContextCompat.checkSelfPermission(this,
                                Manifest.permission.ACCESS_FINE_LOCATION)
                                == PackageManager.PERMISSION_GRANTED) 

                            if (mGoogleApiClient == null) 
                                buildGoogleApiClient();
                            
                        

                     else 

                        // Permission denied, Disable the functionality that depends on this permission.
                        Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
                    
                 catch (Exception e) 
                    e.printStackTrace();
                
            

            // other 'case' lines to check for other permissions this app might request.
            // You can add here other case statements according to your requirement.
        
    

    @Override
    protected void onRestart() 
        super.onRestart();
        try 
//            closeAllActivity(this);
            startLocationUpdates();
            if (alert.isShowing()) 
                alert.cancel();
            
         catch (Exception e) 
            e.printStackTrace();
        
    

    @Override
    protected void onStop() 
        super.onStop();
        try 
            if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) 
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            
         catch (Exception e) 
            e.printStackTrace();
        
    

    protected void startLocationUpdates() 
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 
            return;
        
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    

【问题讨论】:

GPS 通常精确到 5 米。所以,总会有一些错误。 请告诉我们您的尝试。 如果您可以添加您尝试过的代码,我们将更容易理解问题并为您提供帮助。 使用LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener) 方法,这将更新您当前的位置 @GauravJain,我刚刚发布了一个答案。 .看看这个 【参考方案1】:

使用此代码并将 mFusedLocationClient 替换为您的 FusedLocationProviderClient 的对象

mFusedLocationClient.getLastLocation()
        .addOnSuccessListener(getActivity(), new OnSuccessListener<Location>() 
            @Override
            public void onSuccess(Location location) 
                if (location == null) 
                    Log.w(TAG, "onSuccess:null");
                    return;
                

                if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) 

                    return;
                

                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                        2000,
                        10, new LocationListener() 
                            double latitude;
                            double longitude;

                            @Override
                            public void onLocationChanged(Location location) 
                                try 
                                    latitude = location.getLatitude();
                                    longitude = location.getLongitude();

                                    String msg = "New Latitude: " + latitude + "New Longitude: " + longitude;
                                    Log.d("Message", msg);

                                 catch (Exception e) 
                                    e.printStackTrace();
                                    Log.d("Error", "Bad Network Connection");
                                    latitude = mLastLocation.getLatitude();
                                    longitude = mLastLocation.getLongitude();
                                
                            

                            @Override
                            public void onStatusChanged(String provider, int status, Bundle extras) 
                            

                            @Override
                            public void onProviderEnabled(String provider) 
                            

                            @Override
                            public void onProviderDisabled(String provider) 
                            
                        );

            
        )
        .addOnFailureListener(getActivity(), new OnFailureListener() 
            @Override
            public void onFailure(@NonNull Exception e) 
                Log.w(TAG, "getLastLocation:onFailure", e);
            
        );

【讨论】:

以上是关于Android:是不是有任何解决方案可以每次使用 GPS 或网络获取准确位置 [重复]的主要内容,如果未能解决你的问题,请参考以下文章

Android studio下载后每次打开都要重新安装,在不用卸载的情况下怎么解决?

android opencv - 每次旋转是不是有可能捕捉到对 3D 对象的不同点击?

每次构建 iOS 应用程序时,您是不是有任何不想使用静态分析器的原因?

当第三方使用哨兵向我们的服务器执行任何事件时,是不是可以每次都追踪第三方的详细信息?

Android卡在Gradle:Resolve dependencies‘:xxx:xxx‘

屏幕关闭前的 Android BroadcastReceiver