我有一个奇怪的问题,在我的应用程序中,GPS定位需要相当长的时间(因为它往往会这样做),因此我想在用户在其他视图中做出选择时将其作为自己的线程运行。 / p>
我的结构是我有一个在后台始终处于活动状态的“主”视图,然后向用户显示一系列视图,他或她在这些视图中做出一些选择。最后,基于所做出的选择和当前位置向用户呈现结果。所有这些都有效,但我想将GPS位移动到自己的线程,以便用户不必等待它完成。
所有用户的选择和GPS坐标都存储在一个名为CurrentLogEntry的单例中。程序不同部分之间的所有通信都是通过它进行的。
我在主视图中创建了一个handleMessage(Message msg)
覆盖,然后我在Main.java中实现了这个函数:
void startGPSThread() {
Thread t = new Thread() {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean isDebug = CurrentLogEntry.getInstance().isDebug();
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
/* This is called when the GPS status changes */
String tag = "onStatusChanged, ";
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
Log.w(tag, "Status Changed: Out of Service");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.w(tag, "Status Changed: Temporarily Unavailable");
break;
case LocationProvider.AVAILABLE:
break;
}
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
// This is called if the GPS is disabled in settings.
// Bring up the GPS settings
Intent intent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
public void onLocationChanged(Location location) {
// Once a location has been received, ignore all other position
// updates.
locationManager.removeUpdates(locationListener);
locationManager.removeUpdates(this);
// Make sure that the received location is a valid one,
// otherwise show a warning toast and hit "back".
if (location == null) {
String warningString = "Location was unititialized!";
if (isDebug) {
Toast.makeText(getApplicationContext(),
warningString,
Toast.LENGTH_LONG).show();
}
KeyEvent kev = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK);
onKeyDown(KeyEvent.KEYCODE_BACK, kev);
}
CurrentLogEntry.getInstance().setUserLatitude(location.getLatitude());
CurrentLogEntry.getInstance().setUserLongitude(location.getLongitude());
//Send update to the main thread
int result = 0;
if (location.getLatitude() == 0 || location.getLongitude() == 0) {
result = -1;
}
messageHandler.sendMessage(Message.obtain(messageHandler, result));
}
};
@Override
public void run() {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
// Wait until a position has bee acquired.
while(!CurrentLogEntry.getInstance().isReadyToCalculate()){
try {
wait(250);
} catch (InterruptedException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
};
t.start();
}
此功能在Main.onCreate()
。
不幸的是,这根本不起作用。该程序一到达locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
就会崩溃,这让我完全陷入困境。
任何人都可以告诉我为什么这不会作为后台线程运行?另外,我真的需要在最后进行等待轮询以确保线程保持活动状态直到它收到数据吗?在我想把它放在自己的线程之前,GPS位工作得很好,所以世界上我做错了什么?