我正在尝试在 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行会得到一个NullPointerException,可能是因为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);
}
}
谢谢!
onLocationChange
中,并查看 Logcat 是否有输出... - Beasly