【发布时间】:2011-01-20 09:56:56
【问题描述】:
我正在尝试在 android 模拟器上使用 gps,我有以下代码:
public class NL extends Activity {
private LocationManager locmgr = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nl);
locmgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String provider = locmgr.getBestProvider(crit, true);
Location loc = locmgr.getLastKnownLocation(provider);
Toast msg = Toast.makeText(this, "Lon: " + Double.toString(loc.getLongitude()) + " Lat: " + Double.toString(loc.getLatitude()), Toast.LENGTH_SHORT);
msg.show();
}
}
我在清单中添加了以下行:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
我已经使用 DDMS 方法和 geo fix 方法设置了 gps 位置,但是当我运行代码时,我在 Toast 行得到一个 NullPointerExeption,可能是因为 loc 为空。
我不明白错误出在哪里...你能帮帮我吗?
更新!
感谢您的帮助,现在我使用以下代码并且没有收到任何错误,但它没有运行 onChangeLocation 内的代码...它没有运行 Toast 并且不返回任何消息在日志中!
public class NL extends Activity {
private LocationManager locmgr = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nl);
locmgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location loc) {
// Called when a new location is found by the network location provider.
Log.i("NOTIFICATION","onLocationChenged Triggered");
Toast msg = Toast.makeText(NetworkLocator.this, "Lon: " + Double.toString(loc.getLongitude()) + " Lat: " + Double.toString(loc.getLatitude()), Toast.LENGTH_SHORT);
msg.show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locmgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
}
谢谢!
【问题讨论】:
-
您是否验证过 locmgr.getBestProvider 是否真的返回“gps”?无论如何,您绝对应该实现一个 LocationListener 并使用 requestLocationUpdates() 将其传递给 LocationManager
-
getBestProvider 返回“gps”。即使我尝试使用 lastKnownLocation 获取位置,我是否也要添加位置侦听器?感谢您的帮助
-
@Marco Faion 请及时更新您的答案...我已经回答过您一次,但您没有对答案提供任何反馈! >
http://stackoverflow.com/questions/4591765/android-sqlite-database-method-undefined-fot-type/4591843#4591843 -
你好宏你得到解决方案了吗?
-
将日志输出到
onLocationChange并在 Logcat 中查看是否有打印内容...
标签: java android android-emulator gps