【问题标题】:Android Getting Current Location NULL with two different code snippetsAndroid 使用两个不同的代码片段获取当前位置 NULL
【发布时间】:2015-11-02 08:02:54
【问题描述】:

我被 GPS/网络提供商的位置所困扰。我知道这是所有 androiders 的基本问题,但我有这个问题很久了。

实际上我是通过点击选项菜单的以下方法获取当前位置并插入数据库。

/****
 * GPS Process First of all call listener of Location then checking for GPS_PROVIDER if not
 * available then check for NETWORK_PROVIDER and if its also not available then pass
 * 0.00,0.00 to longitude and latitude
 */
/** PROCESS for Get Longitude and Latitude **/
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

// Define a listener that responds to location updates
locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        longitude = String.valueOf(location.getLongitude());
        latitude = String.valueOf(location.getLatitude());
        Log.d(TAG, "changed Loc : " + longitude + ":" + latitude);
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    public void onProviderEnabled(String provider) {
    }

    public void onProviderDisabled(String provider) {
    }
};

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

// check if GPS enabled
if (isGPSEnabled) {
    int i;
    for (i = 0; i < 3; i++) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                locationListener);

        Location location = locationManager
                .getLastKnownLocation(LocationManager.GPS_PROVIDER);

        if (location != null) {
            longitude = String.valueOf(location.getLongitude());
            latitude = String.valueOf(location.getLatitude());
            break;
        } else {
            location = locationManager
                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            if (location != null) {
                longitude = String.valueOf(location.getLongitude());
                latitude = String.valueOf(location.getLatitude());
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
                        0, locationListener);
                break;
            } else {
                longitude = "0.00";
                latitude = "0.00";
            }
        }
    }

    /**
     * Record Inserting Process in Database...
     **/

} else {
    AlertDialogManager.showAlertforSettings(AccountMenuActivity.this, "GPS Settings",
            "GPS is not Enabled. Do you want to Enable?", false);
}

我得到 0.00 纬度和经度 很多次,有时 我得到了其他国家(中国、南非等)的位置

我不知道为什么会这样,但是在我找到 Stackoverflow 解决方案之后顺便说一句,自从谷歌搜索 2 天后发现了 Google 的新 API,名为 FusedLocationProviderApi

我已经通过以下一些链接实现但收到如下错误:

/**
 * Booleans for GPS and NETWORK is Enabled or not...
 */
boolean gpsEnabled = false;
boolean networkEnabled = false;

//exceptions will be thrown if provider is not permitted.
try {
    gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
    Log.e("TAG", "GPS Error : " + ex.getLocalizedMessage());
}

try {
    networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
    Log.e("TAG", "NetWork Error : " + ex.getLocalizedMessage());
}

Log.e("TAG", "GPS Network status : " + gpsEnabled + " : " + networkEnabled);

//don't start listeners if no provider is enabled
if (!gpsEnabled && !networkEnabled) {
    AlertDialogManager.showAlertforSettings(VisitAcitivity.this, "GPS Settings", "GPS is not Enabled. Do you want to Enable?", false);
} else {
    Log.i(TAG, "isPlayServiceAvailable" + isPlayServiceAvailable);
    if(isPlayServiceAvailable) {

        createLocationRequest();

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        mGoogleApiClient.connect();

    } else {

        final MyLocation.LocationResult locationResult = new MyLocation.LocationResult() {

            @Override
            public void gotLocation(final Location location) {
                // Got the location!
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        longitude = String.valueOf(location.getLongitude());
                        latitude = String.valueOf(location.getLatitude());

                        saveVisit();

                    }

                });
            }
        };
        MyLocation myLocation = new MyLocation();
        myLocation.getLocation(VisitAcitivity.this, locationResult);                
    }
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    if(isPlayServiceAvailable && mGoogleApiClient != null) 
        stopLocationUpdates();
    else if (locationManager != null) {
        locationManager.removeUpdates(locationListener);
        Log.d("msg", "Location Listener ended...");
    }
}

@Override
public void onStop() {
    super.onStop();
    Log.d(TAG, "onStop fired ..............");
    if(mGoogleApiClient != null)
        mGoogleApiClient.disconnect();

}

@Override
public void onConnected(Bundle bundle) {
    Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
    startLocationUpdates();
}

protected void startLocationUpdates() {
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    Log.d(TAG, "Location update started ..............: ");
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}

@Override
public void onLocationChanged(Location location) {
    Log.d(TAG, "Firing onLocationChanged..............................................");
    mCurrentLocation = location;
    Log.d(TAG, "UI update initiated .............");
    if (null != mCurrentLocation) {
        latitude = String.valueOf(mCurrentLocation.getLatitude());
        longitude = String.valueOf(mCurrentLocation.getLongitude());
    } else {
        Log.d(TAG, "location is null ...............");
    }
}

protected void stopLocationUpdates() {
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    Log.d(TAG, "Location update stopped .......................");
}

我正在管理两种获取位置的方法:

  1. Google Play 服务是否可用,然后使用 FusedLocation API 获取位置。
  2. 否则使用我自己的方式获取位置(因为设备太多)。

我在我的AndroidManifest.xml 中获得了以下权限:

<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

然后也得到 NULL 个位置:(对于这个问题有什么解决方案吗?

提前致谢。

【问题讨论】:

    标签: android gps android-location android-fusedlocation


    【解决方案1】:

    试试这个:https://github.com/mcharmas/Android-ReactiveLocation

    8行代码获取融合位置:

    ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(context);
    locationProvider.getLastKnownLocation()
        .subscribe(new Action1<Location>() {
            @Override
            public void call(Location location) {
                doSthImportantWithObtainedLocation(location);
            }
        });
    

    【讨论】:

    • 不,那么你需要一些你已经拥有的东西作为替代品,但这真的很少见吗?该设备没有播放商店。只有扎根或类似的东西?
    猜你喜欢
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 2011-07-15
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多