簡體   English   中英

LocationManager在Android 4.4以上版本中提供Wearg位置

[英]LocationManager giving worng location in android version above 4.4

我已經實現了GPSTracker類來獲取當前的緯度和經度。 它給出了Android 4.4及以下版本的結果。 但是,當我在更高版本上安裝相同版本時,它的值是(0,0)。 誰能告訴我我要去哪里錯了。

我的Gpstracker類別:-

public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(Context.LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

我的允許清單是:-`

<permission
    android:name="goyal.andorid.varun.jaintemplelocator.permission.C2D_MESSAGE"
    android:protectionLevel="signature" />

<uses-permission android:name="goyal.andorid.varun.jaintemplelocator.permission.C2D_MESSAGE" />
<!-- This app has permission to register and receive dataf message. -->
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<!-- Network State Permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

請幫幫我

因為您不請求權限。 根據文檔:

從Android 6.0(API級別23)開始,用戶在應用程序運行時(而不是在安裝應用程序時)授予應用程序權限。

android.permission.ACCESS_FINE_LOCATION是危險許可,因此您需要請求它。 官方手冊

您可以使用GoogleApiClient's fused location provider來獲取位置。 您需要在gradle文件中添加依賴項。

compile 'com.google.android.gms:play-services-location:9.6.1'

在清單中添加所需的fine_location權限

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

這是一個危險許可,您需要在運行時像這樣請求許可

代碼段

public class DashboardActivity extends AppCompatActivity implements 
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener,
        ResultCallback<LocationSettingsResult> {

    private GoogleApiClient googleApiClient;
    private GoogleApiAvailability apiAvailability;

    private static final long MIN_TIME_BW_UPDATES = 10000;
    private static final long FAST_TIME_BW_UPDATES = 3000;
    private final static int REQUEST_CHECK_SETTINGS = 100;
    private static final long EXPIRATION_DURATION = 3600000;

    protected LocationRequest mLocationRequest;
    protected LocationSettingsRequest mLocationSettingsRequest;
    private Location location;
    private LatLng latLng = new LatLng(0, 0);
    private double latitude;
    private double longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);
        init();
    }

    private void init() {
        apiAvailability = GoogleApiAvailability.getInstance();
        if (googleApiAvaibility()) {
            buildGoogleApiClient();
            displayLocation();
        }
    }

    protected void createLocationRequest() {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setInterval(MIN_TIME_BW_UPDATES);
        mLocationRequest.setFastestInterval(FAST_TIME_BW_UPDATES);
        mLocationRequest.setSmallestDisplacement(10);
        mLocationRequest.setExpirationDuration(EXPIRATION_DURATION);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        builder.setAlwaysShow(true);
        mLocationSettingsRequest = builder.build();
    }

    protected synchronized void buildGoogleApiClient() {
        googleApiClient = new GoogleApiClient.Builder(getApplicationContext())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    private boolean googleApiAvaibility() {
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
        switch (resultCode) {
            case ConnectionResult.SUCCESS:
                return true;
            case ConnectionResult.API_UNAVAILABLE:
                Dialog dialog = apiAvailability.getErrorDialog(this, ConnectionResult.API_UNAVAILABLE, 200,
                        new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                //finish();
                            }
                        });
                dialog.show();
                break;
            case ConnectionResult.SERVICE_MISSING:
                Dialog dialog1 = apiAvailability.getErrorDialog(this, ConnectionResult.SERVICE_MISSING, 201,
                        new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                //finish();
                            }
                        });
                dialog1.show();
                break;
        }
        return false;
    }

    @Override
    public void onLocationChanged(Location location) {
        latLng = new LatLng(location.getLatitude(), location.getLongitude());
        //here you will get new latitude and longitude if location is changed
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        displayLocation();
                        break;
                    case Activity.RESULT_CANCELED:
                        //finish();
                        Toast.makeText(getActivity(), "Please enable location. Otherwise you can not use this application", Toast.LENGTH_LONG).show();
                        break;
                }
                break;
            default:

                break;
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        createLocationRequest();
        checkLocationSettings();
    }

    @Override
    public void onConnectionSuspended(int i) {
        googleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        googleApiClient.connect();
    }

    @Override
    public void onResult(@NonNull LocationSettingsResult result) {
        Status status = result.getStatus();
        switch (status.getStatusCode()) {
            case LocationSettingsStatusCodes.SUCCESS:
                displayLocation();
                break;
            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                try {
                    status.startResolutionForResult(this, REQUEST_CHECK_SETTINGS);
                } catch (IntentSender.SendIntentException e) {
                    Log.e("Exception", e.toString());
                }
                break;
            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                //showDialog(this,"You have choose never for Location!");
                break;
            default:
                break;
        }
    }

    protected void checkLocationSettings() {
        PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.
                checkLocationSettings(googleApiClient, mLocationSettingsRequest);
        result.setResultCallback(this);
    }

    private void displayLocation() {
        if (ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 250);
        } else {
            location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
            if (location != null) {
                latLng = new LatLng(location.getLatitude(), location.getLongitude());
                latitude = location.getLatitude();
                longitude = location.getLongitude();
                //print latitude longitude here
            } else {
                if (googleApiAvaibility()) {
                    buildGoogleApiClient();
                    googleApiClient.connect();
                    if (googleApiClient.isConnected()) {
                        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, mLocationRequest, this);
                    }
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (permissions[0].equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
                if (location != null) {
                  displayLocation();
                } else {
                    //googleApiClient.connect();
                    if (googleApiAvaibility()) {
                        buildGoogleApiClient();
                        googleApiClient.connect();
                    }
                }

            }
        }
    }
}

您也可以檢查此sample

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM