我有一些代码:
清单
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
活动字段
private LocationManager locationManager;
private LocationListener mlocListener;
onCreate初始化
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
类MyLocationListener
public class MyLocationListener implements LocationListener{
@Override
public void onLocationChanged(Location loc){
}
@Override
public void onProviderDisabled(String provider){
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
@Override
public void onProviderEnabled(String provider){
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras){
}
}
我有按钮,onclick =获取用户gps位置
public void getUserLocation(View v){
boolean enabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
} else {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Toast.makeText(getApplicationContext(), String.valueOf(location.getLatitude()) + " " + String.valueOf(location.getLongitude()), Toast.LENGTH_SHORT).show();
}
}
在getLastKnownLocation上我有错误。我怎样才能检查locationManager是否有getLastKnownLocation? requestLocationUpdates自动获取位置,还没有?
我很有意思,requestLocationUpdates(minTime和minDistance)中哪些参数应该更好用?我不想吃太多的用户电池
答案 0 :(得分:2)
如何检查locationManager是否具有getLastKnownLocation?
只需进行空检查即可完成所需的
requestLocationUpdates自动获取位置,还没有?
您可以从网络或Gps请求。它开始寻找位置更新。 但这可能需要一些时间。
Gps更新速度更慢。需要开阔的天空,但更准确。
网络更新速度更快。但与GPS相比,准确度较低。 无线网络准确度大约在50-100左右,这对大多数scnario来说都是好的。
我很有意思,requestLocationUpdates中的哪些参数(minTime和minDistance) 应该更好用?我不想吃太多的用户电池
使用0,0 一旦获得所需精度的更新,请从收听位置更新中取消注册。
答案 1 :(得分:0)
Use this..
/*
* getting the best location using the location manager
*/
mLocation = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mBestProvider = mLocation.getBestProvider(criteria, false);
Location location = mLocation.getLastKnownLocation(mBestProvider);
mLocation.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
Constants.MINIMUM_TIME_BETWEEN_UPDATES,
Constants.MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new LocationListenerManager()
);
if(location!=null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
else { // handle by urself
}