我写了一个非常简单的应用程序,要求LocationProvider获取一个位置并将其打印到System.out。这在模拟器中很有用。但是,当我在我的黑莓设备上运行它时,对getLocation的调用似乎无限期地挂起。我在一个单独的线程中运行代码,该线程只是获取提供程序并询问位置。我尝试使用null Criteria(它应该给我默认值对吗?)以及应该提供Assist然后自治的Criteria。我在下面提供了我的代码。当我在我的设备上运行它时会挂起对getLocation的调用。这是我的代码,如下所示...... plzz告诉我可能做错了什么......
public void getLocation() {
Thread t = new Thread(new Runnable() {
private double lat;
private double lon;
public void run() {
Criteria cr = new Criteria();
cr.setHorizontalAccuracy(Criteria.NO_REQUIREMENT);
cr.setVerticalAccuracy(Criteria.NO_REQUIREMENT);
cr.setCostAllowed(false);
cr.setPreferredPowerConsumption(Criteria.NO_REQUIREMENT);
cr.setPreferredResponseTime(1000);
LocationProvider lp = null;
try {
lp = LocationProvider.getInstance(cr);
} catch (LocationException e) {
// System.out.println("*****************Exception" + e);
}
Coordinates c = null;
if (lp == null) {
UiApplication.getUiApplication().invokeLater(
new Runnable() {
public void run() {
Dialog.alert("GPS not supported!");
return;
}
});
} else {
// System.out.println("OK");
switch (lp.getState()) {
case LocationProvider.AVAILABLE:
// System.out.println("Provider is AVAILABLE");
Location l = null;
try {
l = lp.getLocation(-1);
} catch (LocationException e) {
// System.out.println("***Location Exception caught "
// + e);
} catch (InterruptedException e) {
// System.out.println("***Interrupted Exception aught:"
// + e);
} catch (Exception e) {
// System.out.println("***Exception caught :"
// ;+ e);
}
if (l != null && l.isValid()) {
c = l.getQualifiedCoordinates();
}
if (c != null) {
lat = c.getLatitude();
lon = c.getLongitude();
System.out.println(lat + " - " + lon);
}
}
}
}
});
t.start();
}
答案 0 :(得分:4)
尝试:
谈论悬挂线程,
locationProvider.getLocation(-1)
挂起,因为如果使用-1,则不会超时。试试这个:
int timeout = 120;
try {
location = provider.getLocation(timeout);
} catch (LocationException e) {
System.out.println("Location timeout");
} catch (InterruptedException e) {
System.out.println("InterruptedException"+e.getMessage());
}
另外,如果您在模拟器中使用System.out.println(text)
,那么在设备上最好
getApplication().invokeLater(new Runnable(){
public void run() {
screen.add(new LabelField(text));
}
});
或
getApplication().invokeLater(new Runnable(){
public void run() {
Dialog.inform(text);
}
});
答案 1 :(得分:0)
-1超时的事情应该没问题,它应该是默认的。默认值可能很高,如果在后台没有发生这种情况,您可能希望将超时设置为较小的值,例如15秒。
这在模拟器中工作但挂在实际设备上的原因可能是您在进行测试的设备上没有GPS修复...
我不是在开玩笑,你在外面试过吗?