Android如何获取Lat()和获取Long()



我试图向用户发送我的long和lat,并且我得到了nullPointerException:

尝试在空对象引用上调用虚拟方法"double android.location.location.getLatitude()"

我想getLastKnownLocation()方法返回null是因为模拟器没有位置启动吗?

如果是这样,我怎么能用另一种方式来做呢?

这是我的代码:

public class MainActivity extends Activity {

Button btnSend;
TextView txtview;
String email = "superman@hotmail.com";
String position;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtview = (TextView) findViewById(R.id.textView);
    btnSend = (Button) findViewById(R.id.button);
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    Double lat = location.getLatitude();
    Double lng = location.getLongitude();
     position = Double.toString(lat + lng);

    btnSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String[] TO = {"batman@hotmail.com"};
            Intent sendMypos = new Intent(Intent.ACTION_SEND);
            sendMypos.putExtra(Intent.EXTRA_EMAIL,TO);
            sendMypos.putExtra(Intent.EXTRA_SUBJECT,"Min position");
            sendMypos.putExtra(Intent.EXTRA_TEXT, position);
            sendMypos.setData(Uri.parse("mailto:"));
            sendMypos.setType("message/rfc822");
            startActivity(Intent.createChooser(sendMypos,"Email klient"));
        }

    });
}

}

我的清单:

 <uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>

我猜metid getLastKnownLocation返回null是因为模拟器没有位置启动吗?

是,或者该提供程序被禁用,或者自设备重新启动以来从未使用过该提供程序,等等。getLastKnownLocation()可以很容易地返回null

如果是这样,我怎么能用另一种方式来做呢?

欢迎您使用getLastKnownLocation()。您只需要检查null的结果,不要盲目使用它。

也欢迎您使用requestSingleUpdate()尝试通过短暂接通GPS电源来定位。

但是,您不能强迫用户和设备为您提供位置。如果用户选择禁用GPS,这是用户的选择。如果设备无法获得GPS定位,则不能强制用户移动到可以访问GPS的位置。等等。

Emulator实际上不适合测试GPS(因为模拟器在没有GPS设备的PC中运行。)

而是在实际设备中进行测试。在大多数情况下,真正的设备运行良好。但是,如果您面临同样的问题,那么深入调试将有所帮助。

最新更新