我正在开发一个针对最小android API 11的应用程序。该应用程序需要找出用户城市。
我在代码中使用LocationClient
来获取Location对象。
代码:
public class SplashScreen extends ActionBarActivity implements LocationListener{
LocationClient locationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
locationClient=new LocationClient(SplashScreen.this,new GooglePlayServicesClient.ConnectionCallbacks() {
@Override
public void onConnected(Bundle bundle) {
Log.d("check","Connection successful"); // Getting Printed
Location location=locationClient.getLastLocation();
if(location==null)
{
Log.d("check","location is null"); // Getting Printed
}
else {
Log.d("check",location.toString());
}
LocationRequest locationRequest=new LocationRequest();
locationRequest.setFastestInterval(2*1000);
locationRequest.setSmallestDisplacement(0);
locationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER); locationClient.requestLocationUpdates(locationRequest,SplashScreen.this);
}
@Override
public void onDisconnected() {}
},
new GooglePlayServicesClient.OnConnectionFailedListener() {
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d("clickindia", "Connection Failed" + connectionResult);}
});
public void onStart()
{
super.onStart();
locationClient.connect();
}
public void onLocationChanged(Location location) {
if(location==null)
{
Log.d("check","location is null"); //Not getting Printed
}
else {
Log.d("check",location.toString()); //Not getting Printed
}
}
问题是首先返回null location对象,然后调用onlocationchanged()
事件处理程序。
清单文件权限:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Gradle文件依赖性声明:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.2.0'
compile 'com.google.android.gms:play-services:4.0+'
}