2011-03-09 55 views
0

我无法弄清楚为什么当GPS未启用时,我的应用程序强制关闭。在运行之前启用时,一切正常。一切工作正常,直到我添加LocationListener更新当前位置。我敢肯定,这简直太荒唐了。当GPS未启用时,应用程序强制关闭

public class GlenrochieMain extends Activity 

{ 


    @Override 

    protected void onCreate(Bundle savedInstanceState) { 
     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 Location is:\n" + 
          latLongString); 
    } 
} 
+0

您可以粘贴强制关闭的异常吗? – srinathhs 2011-03-09 04:14:51

+0

什么在日志中?你的设备是否有SIM卡,在这种情况下,当GPS关闭时将没有提供商? – bhups 2011-03-09 04:15:27

回答

0
String provider = locationManager.getBestProvider(criteria, true); 

当找不到合适的提供者时,getBestProvider将返回null。你还没有处理过这种情况。

+0

你能解释一下我需要改变以解决这个问题吗? – Kal 2011-03-09 19:22:29

+0

之后,检查'provider'是否为空。如果是这样,请求用户启用gps /打开gps启用对话框。如果它为null,则不能调用'getLastKnownLocation' – 2011-03-10 03:22:27