之前我问过这个问题,我有几个答案,但没有解决方案。有人可以帮我理解我需要做些什么来解决这个问题吗?我的应用程序强制关闭,除非在启动应用程序之前启用了GPS。我正在学习如何编程android和一些我得到的答案,我只是不明白。我希望有人会指出哪一段代码导致问题以及我需要做些什么来解决它。如果需要更多信息,请告诉我您的需求。并且认真地,感谢帮助并且对这个'初学者'有耐心。
public class GlenrochieMain extends Activity
{
//called when activity is first created
@Override
protected void onCreate(Bundle savedInstanceState) {
// shows main layout
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//GPS Functionality
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
//Criteria for GPS
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
//updates location every 5second+5meters
locationManager.requestLocationUpdates(provider, 5000, 5,
locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider){
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};
private void updateWithNewLocation(Location location) {
String latLongString;
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
} else {
latLongString = "No location found";
}
myLocationText.setText("Your Current Position is:\n" +
latLongString);
}
}
答案 0 :(得分:0)
您必须捕获非运营GPS的例外情况。执行异常捕获对于大多数编程语言的稳定性非常重要。
答案 1 :(得分:0)
我的建议是检查您的GPS服务是否已启用,如果是,则调用requestLocationUpdates。示例代码如下:
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
// request updates here..
}
其次,您正在寻找“Criteria.ACCURACY_FINE”,因此只有GPS才能提供此功能。您可以将提供程序替换为“LocationManager.GPS_PROVIDER”
另外,请注意GPS不是低功耗。