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

Mar*_*ion 8 java gps android android-emulator

我想在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();
    }
}
Run Code Online (Sandbox Code Playgroud)

我在清单上添加了以下行:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Run Code Online (Sandbox Code Playgroud)

并且我使用DDMS方法和geo fix方法设置gps位置,但是当我运行代码时,我在Toast行获得NullPointerExeption,可能导致loc为null.

我不明白错误在哪里......你能帮帮我吗?


UPDATE!

感谢您的帮助,现在我使用以下代码,我没有得到任何错误,但它没有运行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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

谢谢!

Dam*_*ski 9

模拟器在开始时没有任何位置.根据doc,'getLastKnownLocation'方法可以返回null,所以没关系.在这种情况下,您应该等待位置更新(您可以从LocationManager用户requestLocationUpdates方法).您可以通过以下命令在模拟器的gps模块上触发位置更新:

adb -e emu geo fix 50 50
Run Code Online (Sandbox Code Playgroud)


Mar*_*ion 7

找到解决方案:

LocationManager.NETWORK_PROVIDER错误.

更正:LocationManager.GPS_PROVIDER