osc*_*cat 57 gps android location
就像我在测试一个nexus s(4.0.4提供google play服务)和avd(4.2.2 with google api)之前遇到的问题一样,在这两种情况下,locationclient getLastLocation()总是返回null.
public class MainActivity extends Activity implements LocationListener,
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener {
    private LocationClient mLocationClient;
    private LocationRequest mLocationRequest;
    boolean mUpdatesRequested = false;
    boolean mConnected = false;
    SharedPreferences mPrefs;
    SharedPreferences.Editor mEditor;
    private TextView mText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mText = (TextView) findViewById(R.id.text);
        mLocationRequest = LocationRequest.create();
        mLocationRequest
                .setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest
.setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
        mUpdatesRequested = false;
        mPrefs = getSharedPreferences(LocationUtils.SHARED_PREFERENCES,
                Context.MODE_PRIVATE);
        mEditor = mPrefs.edit();
        mLocationClient = new LocationClient(this, this, this);
    }
    @Override
    public void onStart() {
        super.onStart();
        /*
         * Connect the client. Don't re-start any requests here; instead, wait
         * for onResume()
         */
        mLocationClient.connect();
    }
    @Override
    protected void onResume() {
        super.onResume();
        // If the app already has a setting for getting location updates, get it
        if (mPrefs.contains(LocationUtils.KEY_UPDATES_REQUESTED)) {
            mUpdatesRequested = mPrefs.getBoolean(
                    LocationUtils.KEY_UPDATES_REQUESTED, false);
            // Otherwise, turn off location updates until requested
        } else {
            mEditor.putBoolean(LocationUtils.KEY_UPDATES_REQUESTED, false);
            mEditor.commit();
        }
    }
    @Override
    public void onStop() {
        // If the client is connected
        if (mLocationClient.isConnected()) {
            stopPeriodicUpdates();
        }
        // After disconnect() is called, the client is considered "dead".
        mLocationClient.disconnect();
        super.onStop();
    }
    @Override
    public void onPause() {
        // Save the current setting for updates
        mEditor.putBoolean(LocationUtils.KEY_UPDATES_REQUESTED,
                mUpdatesRequested);
        mEditor.commit();
        super.onPause();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    public void getLocation(View v) {
        // If Google Play Services is available
        if (isGooglePlayServicesAvailable()) {
            if (!mConnected)
                mText.setText("location client is not connected to service yet");
            else {
                // Get the current location
                Location currentLocation = mLocationClient.getLastLocation();
                // Display the current location in the UI
                mText.setText(LocationUtils.getLocationString(currentLocation));
            }
        }
    }
    private boolean isGooglePlayServicesAvailable() {
        // Check that Google Play services is available
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);
        // If Google Play services is available
        if (ConnectionResult.SUCCESS == resultCode) {
            // In debug mode, log the status
            Log.d(LocationUtils.APPTAG, "google play service is available");
            // Continue
            return true;
            // Google Play services was not available for some reason
        } else {
            // Display an error dialog
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode,
                    this, 0);
            if (dialog != null) {
                Log.e(LocationUtils.APPTAG,
                        "google play service is unavailable");
            }
            return false;
        }
    }
    private void stopPeriodicUpdates() {
        mLocationClient.removeLocationUpdates(this);
        // mConnectionState.setText(R.string.location_updates_stopped);
    }
    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        mConnected = false;
        Log.d(LocationUtils.APPTAG, "connection failed");
    }
    @Override
    public void onConnected(Bundle arg0) {
        mConnected = true;
        Log.d(LocationUtils.APPTAG,
                "location client connected to the location server");
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0,
                new android.location.LocationListener() {
                    @Override
                    public void onStatusChanged(String provider, int status,
                            Bundle extras) {}
                    @Override
                    public void onProviderEnabled(String provider) {}
                    @Override
                    public void onProviderDisabled(String provider) {}
                    @Override
                    public void onLocationChanged(final Location location) {
                    }
                });
        Log.d(LocationUtils.APPTAG, "done trying to get location");
    }
    @Override
    public void onDisconnected() {
        // TODO Auto-generated method stub
        mConnected = false;
        Log.d(LocationUtils.APPTAG,
                "location client disconnected from the location server");
    }
    @Override
    public void onLocationChanged(Location arg0) {}
}
其中大多数来自谷歌给出的例子.在上面的代码中,hava尝试了这样的方法:
LocationRequest request = LocationRequest.create();
request.setNumUpdates(1);
mLocationClient.requestLocationUpdates(request, this);
和
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0,
                new android.location.LocationListener() {
                    @Override
                    public void onStatusChanged(String provider, int status,Bundle extras) {}
                    @Override
                    public void onProviderEnabled(String provider) {}
                    @Override
                    public void onProviderDisabled(String provider) {}
                    @Override
                    public void onLocationChanged(final Location location) {}
                });
在onConnected()打电话之前getLastLocation(),但仍然没有运气.哪里是错误,提前谢谢.
Dav*_*vid 53
目前,Fused Location Provider如果至少有一个客户端连接到它,则仅保留后台位置.一旦第一个客户端连接,它将立即尝试获取位置.如果您的活动是第一个客户端连接,并调用getLastLocation()在马上onConnected(),可能没有足够的时间在第一位置进去.
Sar*_*ran 21
按照教程中的说明我遇到了同样的问题.在电话上它工作,并在(Genymotion)模拟器它没有.
在AndroidManifest.xml中,更改以下内容:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
对此:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
......然后你马上就到了.无需更改代码(以收听位置更新).
Tim*_*ong 19
您的设备未启用"Wi-Fi和移动网络位置"也可能导致此问题.
LocationClient(融合位置提供商)使用GPS和WiFi.GPS需要一段时间才能找到您的位置,而wifi速度要快得多.但是,如果连接了这两个服务中的任何一个,则将调用onConnected的回调方法.如果您尝试立即在onConnected方法中调用LocationClient.getLastLocation(),那么如果您的wifi位置服务被禁用,则很可能会获得null值.这只是因为GPS不够快.
要在本地解决问题,请启用"Wi-Fi和移动网络位置".您可以转到"设置>个人>位置访问> Wi-Fi和移动网络位置"来执行此操作.
但是,如果要为应用程序的用户解决问题,最好检查getLastLocation()是否返回null.如果是,请提示您的用户启用该服务,就像谷歌地图一样.
希望,这有帮助.
我面临着类似的问题.
mLocationClient.getLastLocation()在onConnected建立与Google Play服务的连接之后或之后拨打电话.如果您在连接位置客户端之前调用此方法,则返回的位置将是null.
您可以检查位置客户端是否已连接mLocationClient.isConnected().
希望这可以帮助.
这是完全有效的解决方案,可能在不同的情况下.但是我想添加一些解释步骤,以便任何人都能获得确切的概念:
1)Android组件的onCreate()(例如,Activity,Fragment或Service.注意:不是IntentService),构建然后连接 GoogleApiClient,如下所示.
buildGoogleApiClient();
mGoogleApiClient.connect();
其中,buildGoogleApiClient()实现是,
protected synchronized void buildGoogleApiClient() {
        Log.i(TAG, "Building GoogleApiClient");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }
稍后在onDestroy()上,您可以断开GoogleApiClient的连接,
@Override
    public void onDestroy() {
        Log.i(TAG, "Service destroyed!");
        mGoogleApiClient.disconnect();
        super.onDestroy();
    }
第1步确保您构建并连接GoogleApiClient.
1)GoogleApiClient实例第一次在方法onConnected()上连接.现在,您的下一步应该是onConnected()方法.
@Override
    public void onConnected(@Nullable Bundle bundle) {
        Log.i(TAG, "GoogleApiClient connected!");
        buildLocationSettingsRequest();
        createLocationRequest();
        location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        Log.i(TAG, " Location: " + location); //may return **null** because, I can't guarantee location has been changed immmediately 
    }
上面,您调用了一个方法createLocationRequest()来创建位置请求.createLocationRequest()方法如下所示.
protected void createLocationRequest() {
        //remove location updates so that it resets
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); //Import should not be **android.Location.LocationListener**
    //import should be **import com.google.android.gms.location.LocationListener**;
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10000);
        mLocationRequest.setFastestInterval(5000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        //restart location updates with the new interval
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
3)现在,在LocationListener接口的onLocationChange()回调中,您将获得新位置.
@Override
    public void onLocationChanged(Location location) {
        Log.i(TAG, "Location Changed!");
        Log.i(TAG, " Location: " + location); //I guarantee,I get the changed location here
    }
你可以在Logcat得到这样的结果: 03-22 18:34:17.336 817-817/com.LiveEarthquakesAlerts I/LocationTracker:位置:位置[fuse 37.421998,-122.084000 acc = 20 et = + 15m35s840ms alt = 0.0]
为了能够执行这三个步骤,您应该已经配置了build.gradle,如下所示:
 compile 'com.google.android.gms:play-services-location:10.2.1'
您必须检查用户是否通过Wi-Fi/GSM或GPS启用了位置.如果没有任何可用的位置提供者,那么你就得到了null.
此代码显示具有位置设置的屏幕:
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
在使用三星手机(高度定制的android,并且没有开发人员支持)的测试中,我遇到了类似的问题。
LocationManager和LocationClient无法从提供程序获取GPS。每当您需要它们的位置时,都需要启动它们。在您进行LocationManager.getLastKnownLocationOR LocationClient.getLastLocation呼叫之前执行此操作。这些API将返回。
YOUR_APPLICATION_CONTEXT.getLocationManager().requestLocationUpdates(
    LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
        @Override
        public void onProviderEnabled(String provider) {
        }
        @Override
        public void onProviderDisabled(String provider) {
        }
        @Override
        public void onLocationChanged(final Location location) {
        }
    });
| 归档时间: | 
 | 
| 查看次数: | 75164 次 | 
| 最近记录: |