Android-无法在模拟器上获取GPS位置

我正在尝试在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行上得到了一个N​​ullPointerExeption,可能是因为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);

}

}

谢谢!

回答:

找到解决方案:

LocationManager.NETWORK_PROVIDER错误。

更正:LocationManager.GPS_PROVIDER

以上是 Android-无法在模拟器上获取GPS位置 的全部内容, 来源链接: utcz.com/qa/422023.html

回到顶部