简体   繁体   English

android getlastknownlocation 在模拟器中始终为空

[英]android getlastknownlocation always null in emulator

It seems a common issue, but i really can't understand why is it happening even though i read ton of simialr issues.这似乎是一个常见问题,但我真的不明白为什么会发生,即使我阅读了大量类似的问题。

I am playing with a basic location class on a emulator device, i set everything - permissions (FINE and COARSE) , i have set the coordinates in the DDMS i also tried using the telnet and then , but no matter what it always crashes witth nullpointer exception on the line with getlastknownlocation, any ideas whats wrong here ?我正在模拟器设备上使用基本位置类,我设置了所有内容 - 权限(FINE 和 COARSE),我已经在 DDMS 中设置了坐标,我也尝试使用 telnet 然后,但无论如何它总是因空指针而崩溃getlastknownlocation 线上的异常,有什么想法这里有什么问题吗?

public class MainActivity extends Activity implements LocationListener {



private static LocationManager ok;
private Location L;

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



    ok=(LocationManager)this.getSystemService(ok.GPS_PROVIDER);
    L=ok.getLastKnownLocation(ok.GPS_PROVIDER);












}

@Override
public void onLocationChanged(Location Loc) {


    try {


        double latop=Loc.getLatitude();
        double longe=Loc.getLongitude();

        Log.i("OK", "and"+longe+""+latop);


    } catch (NullPointerException e)

    {

    }




}

getLastKnownLocation() will return null in general, if no app has requested a location fix from your desired provider recently. getLastKnownLocation()通常将返回null ,如果最近没有应用程序从您想要的提供程序请求位置修复。

On the emulator, it seems to take it one step further: you do not get a location unless one has been delivered to the emulator since your app has called requestLocationUpdates() .在模拟器上,它似乎更进了一步:除非您的应用程序调用了requestLocationUpdates()否则除非已将位置传送到模拟器,否则您不会获得位置。

The general pattern for using getLastKnownLocation() , if you want decent odds of getting an actual Location , is to use requestLocationUpdates() and removeLocationUpdates() to ensure that LocationManager is actively seeking locations via your chosen provider.使用getLastKnownLocation()的一般模式,如果您希望获得实际Location几率相当可观,则使用requestLocationUpdates()removeLocationUpdates()来确保LocationManager通过您选择的提供商主动寻找位置。 Of course, you could also use LocationListener and onLocationChanged() , rather than getLastKnownLocation() , if you so chose.当然,如果您愿意,您也可以使用LocationListeneronLocationChanged()而不是getLastKnownLocation()

@CommonsWare's answer is clear. @CommonsWare 的回答很明确。 To get not-null on emulator go to Google Maps application and after that you get some location要在模拟器上获得非空,请转到Google Maps应用程序,然后您会获得一些位置

There is another option, to create your own provider using locationManager.addTestProvider();还有另一种选择,使用 locationManager.addTestProvider() 创建你自己的提供者; so you can make your own tests.这样您就可以进行自己的测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM