如何在没有gps的情况下获取用户位置?我的意思是使用数据服务或网络。可能吗?任何人都可以提供任何示例代码来查看它吗?
答案 0 :(得分:1)
这是我现在正在使用的精简位置服务。在这种情况下,GPS和网络被称为提供商。
我改变了我的逻辑工作方式,它检查启用了哪个提供程序,然后返回启用的最佳提供程序(GPS比网络更好)到此行:String providerToSend = providers.get(1); ,在GetProvider方法中。 因此,不是检查每个提供者,而是选择providers.get(1),它始终是字符串NETWORK。将其提供给您的locationManager.getLastKnownLocation(TheStringWithTheCorrectProviderGoesHere),它将返回您的位置。
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import java.util.List;
public class LocationService extends Service implements LocationListener{
protected LocationManager locationManager;
public String providerNow;
private List<String> providers;
public Location location;
private final Context mContext;
public LocationService(Context context) {
Log.i("TestMap", "LocationService");
this.mContext = context;
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1000,0,this);
providerNow = (GetProvider());
}
public Location getLocation() {
location = locationManager.getLastKnownLocation(providerNow);
return location;
}
public String GetProvider (){
Criteria criteria = new Criteria();
criteria.setAccuracy(2);
providers = locationManager.getProviders(true);
String providerToSend = providers.get(1);
return providerToSend;
}
public IBinder onBind(Intent intent) {
Log.i("TestMap", "onBind");
//TODO for communication return IBinder implementation
return null;
}
public void onLocationChanged(Location location) {
Location locationNew = location;
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
providerNow = (GetProvider());
}
@Override
public void onProviderDisabled(String provider) {
providerNow = (GetProvider());
}
}
答案 1 :(得分:0)
Android存储最后一个位置,您可以获取它http://developer.android.com/reference/android/location/LocationManager.html#getLastKnownLocation(java.lang.String)
许多示例首先阅读lastKnown然后查找来自提供程序how to get gps location android
的更多数据