我在不同的 API 上使用 AVD 进行测试。在 4.0.3 上运行良好,但是当我使用 2.3.3 对其进行测试时,应用程序崩溃并且 AVD 每次都重新启动。
这是我的服务类:
public class SendIntentService extends Service{
@Override
public int onStartCommand(Intent intent, int flags, int startId){
MyLocationListener myLocationListener = new MyLocationListener(this);
Location location = myLocationListener.getLocation();
double latitude = location.getLatitude();
double longtitude = location.getLongtitude();
Log.e("TEST", "lat: " + latitude + " | long: " + longtitude);
return super.onStartCommand(intent, flags, startId);
}
}
这就是我获取用户位置的方式:
public class MyLocationListener implements LocationListener {
private Context context;
private Location location;
private LocationManager locationManager;
private double longtitude = 0.0;
private double latitude = 0.0;
public MyLocationListener(Context context){
this.context = context;
}
public Location getLocation(){
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
boolean isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGpsEnabled && !isNetworkEnabled) return null;
if (isNetworkEnabled){
locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER,
Constants.MIN_INTERVAL,
Constants.LOC_DISTANCE,
this);
if (locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longtitude = location.getLongitude();
}
}
}
if (isGpsEnabled){
if (location == null){
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,
Constants.MIN_INTERVAL,
Constants.LOC_DISTANCE,
this);
if (locationManager != null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longtitude = location.getLongitude();
}
}
}
}
return location;
}
public double getLatitude(){
return latitude;
}
public double getLongitute(){
return longtitude;
}
@Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
权限在 AndroidManifest 中设置。正如我所说,在 4.0.3 上运行良好,但在 2.3.3 上,应用程序崩溃了。我不知道为什么。