我正在获取设备的经度和纬度,但这需要 30 秒到 1 分钟的时间。有什么减少时间的建议吗?
public class MainActivity extends Activity
{
public String zipcode;
public double latG;
public double lonG;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled)
{
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.getLastKnownLocation(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener()
{
public void onLocationChanged(Location location)
{
if (location != null)
{
latG = location.getLatitude();
lonG = location.getLongitude();
Toast.makeText(MainActivity.this,
latG + " " + lonG,
Toast.LENGTH_LONG).show();
}
}
public void onProviderDisabled(String provider)
{
}
public void onProviderEnabled(String provider)
{
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try
{
addresses = geocoder.getFromLocation(latG, lonG, 1);
}
catch (IOException e)
{
Context context = this;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setTitle("Error");
alertDialogBuilder.setMessage("Error in getting address information.");
alertDialogBuilder.setCancelable(true);
}
for (Address address : addresses)
{
if(address.getPostalCode() != null)
{
zipcode = address.getPostalCode();
Toast.makeText(MainActivity.this, zipcode, Toast.LENGTH_LONG).show();
break;
}
}
}
}
最佳答案
您正在使用 GPS_PROVIDER
获取 GPS 数据。 GPS_PROVIDER
直接从卫星获取详细信息,因此您第一次加载它需要一些时间。此外,如果您不在开阔的天空下,GPS_PROVIDER
需要超过 30 秒。当您在办公室或地下室时,GPS_PROVIDER
可能会返回 NULL。
还有一种替代方法是使用 NETWORK_PROVIDER
。该提供商将根据您当前的网络状态为您提供 GPS 详细信息。这不会像 GPS_PROVIDER
那样准确,但它工作得更快。
关于java - 获取经纬度需要很长时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21898272/