更新时间:2023-01-01 10:27:30
您可以使用新的位置提供程序(FusedLocationProvider),它将来自不同位置提供程序的信息组合在一起,因此,如果您的设备有可能获取位置,您将获得知道.当然,您应该为设备启用首选项以使用应用程序的位置信息.
You could use new location provider (FusedLocationProvider), which combines info from different location providers, so if your device has any possibility to obtain location, You'll get know it. Of course, You should enable in preferences for your device to use location info by apps.
检查developers.android.com以获取有关此提供程序的扩展信息.
Check developers.android.com for extended info about this provider.
这对我来说是很好的解决方案:
This is solution working fine for me:
public class FusedLocationListener implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
public interface LocationListener {
public void onReceiveLocation(Location location);
}
private LocationListener mListener;
public static final String TAG = "Fused";
private LocationClient locationClient;
private LocationRequest locationRequest;
protected int minDistanceToUpdate = 1000;
protected int minTimeToUpdate = 10*1000;
protected Context mContext;
@Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "Connected");
locationRequest = new LocationRequest();
locationRequest.setSmallestDisplacement(1);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(30000);
locationRequest.setNumUpdates(1);
locationClient.requestLocationUpdates(locationRequest, this);
}
@Override
public void onDisconnected() {
Log.d(TAG, "Disconnected");
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.d(TAG, "Failed");
}
private static FusedLocationListener instance;
public static synchronized FusedLocationListener getInstance(Context context, LocationListener listener){
if (null==instance) {
instance = new FusedLocationListener(context, listener);
}
return instance;
}
private FusedLocationListener(Context context, LocationListener listener){
mContext = context;
mListener = listener;
}
public void start(){
Log.d(TAG, "Listener started");
locationClient = new LocationClient(mContext,this,this);
locationClient.connect();
}
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Location received: " + location.getLatitude() + ";" + location.getLongitude());
//notify listener with new location
mListener.onReceiveLocation(location);
}
public void stop() {
locationClient.removeLocationUpdates(this);
}
}
用法:
public class MyActivity extends Activity implements FusedLocationListener.LocationListener {
@Override
public void onCreate(Bundle savedInstanceState) {
FusedLocationListener locationListener FusedLocationListener.getInstance(getApplicationContext(), this);
locationListener.start();
}
@Override
public void onReceiveLocation(Location location) {
//handle location here
}
}