我有一些代码:
显现
<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)中的哪些参数应该更好地使用?我不想吃太多用户电池