LocationClient的getLastLocation()方法返回null。

7

我是 Android 编程的新手,想通过创建一个非常基本的应用程序来展示当前位置的纬度和经度。

我正在为我的三星 Galaxy S3 开发,并阅读到需要 启动手机以返回 GPS

我已经尝试在 onConnected() 方法中使用 LocationManager 的 requestLocationUpdates() 方法调用来实现此功能。然而,我发现 LocationClient 仍然返回空位置。

有人能告诉我我做错了什么吗?

这是我的 MainActivity:

import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;

public class MainActivity extends FragmentActivity implements
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener {

    private LocationClient mLocationClient;
    private Location mCurrentLocation;

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

        mLocationClient = new LocationClient(this, this, this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mLocationClient.connect();
    }

    @Override
    protected void onStop() {
        mLocationClient.disconnect();
        super.onStop();
    }

    @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;
    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onConnected(Bundle arg0) {
        Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
        LocationManager manager = (LocationManager) this
                .getSystemService(Context.LOCATION_SERVICE);
        manager.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) {
                    }
                });
        mCurrentLocation = mLocationClient.getLastLocation();

        TextView latTextView = (TextView) findViewById(R.id.latitude_text);
        latTextView.setText(Double.toString(mCurrentLocation.getLatitude()));

        TextView longTextView = (TextView) findViewById(R.id.longitude_text);
        longTextView.setText(Double.toString(mCurrentLocation.getLongitude()));
    }

    @Override
    public void onDisconnected() {
        Toast.makeText(this, "Disconnected. Please re-connect.",
                Toast.LENGTH_SHORT).show();
    }

}

我的Android清单文件如下所示:

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />


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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.willigetwet.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

在运行调试器时,我发现在调用mLocationClient.getLastLocation()后,mCurrentLocation为空。
非常感谢你的帮助!
1个回答

11

mLocationClient.getLastLocation();如果设备上没有保存任何上次位置,可能会返回null。如果您阅读其文档,它说;

它返回当前可用的最佳最新位置。 如果位置不可用,这应该很少发生,将返回null

此外,在onLocationChanged方法中,当您的位置发生变化时,您可能希望将位置设置为最新位置。

@Override
public void onLocationChanged(final Location location) {
      mCurrentLocation = location;
}

1
就是这样-我没有保存任何最后位置。 我前几天得到了一台替代的S3,完全忘记了我没有使用位置服务。 点击一下谷歌地图以设置GPS,现在它正常工作:)。 谢谢! - Sarah Tattersall
@AnujSharma 已更改。感谢您的评论。 - Shobhit Puri
@Shobhit,你能否提供在这种情况下的解决方法?我的意思是,我们应该怎么处理这种情况? - Gem
@SarahTattersall 你能分享一下你的解决方案吗? - Hyder khan
getLastLocation() 方法从哪里获取位置坐标?是从设备中获取的吗?如果是,那么我可以知道设备如何获取这些坐标吗? - ThinkAndCode
1
最新的实现方法是使用fusedLocationProviderClient。但是,它仍然表现相同,如果您的设备中没有缓存任何上次位置(从未打开地图、访问位置或简单关闭GPS),它将返回null。fusedLocationProviderClient.lastLocation.addOnSuccessListener { locationData = mLocationData(it?.latitude.orZero(), it?.longitude.orZero()) } - moonLander_

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接