2011-03-10 69 views
0

我之前已经问过这个问题,而且我有几个答案,但没有解决方案。有人能帮助我了解我需要做些什么来解决这个问题吗?除非在应用程序启动之前启用GPS,否则我的应用程序部队会关闭。我正在学习如何编程android和我得到的一些答案,我只是不明白。我希望有人会指出哪一段代码导致了这个问题,以及我需要做些什么来解决这个问题。如果需要更多信息,请告诉我您需要什么。并认真地,感谢您帮助和耐心这个'初学者'。除非启用GPS,否则App Force会关闭

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

您必须注意非运行GPS的例外。执行异常捕获对于大多数编程语言的稳定性非常重要。

+0

再次,请问请向我解释这个,所以我可以理解。 Vinay提供了他想说的一个小例子,我完全理解他在说什么。即时通讯视觉学习...哈哈 – Kal 2011-03-10 13:57:38

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不是低功耗。

+0

你能告诉我在我的代码中看起来像什么吗?我希望不要替换或重写我所拥有的。 – Kal 2011-03-10 14:07:00

+0

@Kal,首先让我知道你的要求。你需要低功率还是高精度?根据这一点,你需要改变几行。 – Vinay 2011-03-16 05:39:20