这是一直困扰我一些关于线程的东西。等待线程是否会破坏线程的目的? Android线程出现问题
我有一个线程使用LocationManager来查找Android设备的当前位置。然后我更新UI以显示该位置。
事实上,我已经建立了一个名为LocationFinder的整个类来获取我的位置。这样我可以说
String yourLocation = (new LocationFinder).getLocation();
但是,LocationFinder中的getLocation()方法在单独的线程上运行。所以我不能实说
String yourLocation = (new LocationFinder).getLocation();
,因为返回肯定不会是位置,位置需要一秒钟的几部分的直接价值发现。 getLocation()默认返回“notset”,直到内部方法将返回值设置为实际位置。
无论如何,我很困惑如何解决这个问题。我不想阻止,直到找到位置,因为它非常烦人的应用程序锁定几毫秒。我不想使用AsyncTask,因为在调用getLocation()时已经使用,并且我认为嵌套AsyncTasks是错误的。
下面是这个层次的伪代码:
public class MainActivity extends Activity {
Button locationButton = new Button(locationButtonClickListener);
LocationFinder locationFinder = new LocationFinder();
OnClickListener locationButtonClickListener = new OnClickListener() {
locationButton.setText(locationFinder.getLocation());
}
}
public class LocationFinder {
String city = "notYetSet";
public String getLastLocation() {
(new LastKnownLocationFinder).execute();
return city;
}
public String getGPSLocation() {
(new GPSLocationFinder).execute();
return city;
}
private class LastKnownLocationFinder extends AsyncTask {
protected String doInBackground {
city = [lots of code to get last known location];
}
}
private class GPSLocationFinder extends AsyncTask {
protected String doInBackground {
city = [lots of code to get location using GPS];
}
}
}
希望这说明了什么,我在获得。
谢谢。
谢谢,这是非常有帮助!我还没有实现它,但它很有意义,我非常喜欢这种方式。 – andy
我仍然很喜欢这个解决方案,但我很担心的是与我所有最重要的类(这是活动)实现一个接口。我知道接口的存在是出于这个原因,但我觉得如果我可以在LocationFinder类中包含我需要的所有内容,而不需要接口,它会更干净。也许这是不可能的。 – andy
你可以,你只需要发送一个你想要改变到'LocationFinder'的类的引用,然后在那里做修改。当然,如果你发送的是查看参考,请务必使用做'runOnUiThread(..)的变化'如果你正在做的'doInBackground变化()',否则,只是做了改变。 – LuckyMe