我正在编写使用我的GPS位置的Android应用程序。我的代码非常简单。适用于Android的设计模式 - 确保设置GPS位置
public class MyActivityThing extends Activity {
Location l;
MyLocationListener locationListener;
LocationManager locationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.car, menu);
return true;
}
public void setHotColdLocation(View view)
{
l = locationListener.getCurrentLocation();
}
}
这里是我的MyLocationListener
public class MyLocationListener implements LocationListener {
private static Location thelocation;
@Override
public void onLocationChanged(Location location) {
thelocation = location;
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
public Location getCurrentLocation()
{
return thelocation;
}
}
我的情况是这样的。我有一个按钮onClick
在MyActivityThing
中调用setHotColdLocation
方法。
我的问题是,我应该如何确保用户按下按钮时的位置? onLocationChanged
方法不会立即调用,所以当应用程序第一次启动时,我可以按下按钮,并导致异常....
我应该让该按钮不可见,直到该位置被调用? 我是否应该将setHotColdLocation
的内容放在try catch中并丢弃用户点击直到设置位置? 我可以想出很多方法来使其工作,但我不知道最好的一个......或者是正确的。
任何帮助?
为什么不只是在一个空检查? = – nedaRM