2016-05-21 21 views
0

老问题:Android的定位服务 - LocationListener的不工作

我想把我的设备的位置坐标,而且我是按照所有我在多个领域已经找到,而研究的步骤。我建立了一个LocationManager并使用绑定到LocationListener的requestLocationUpdates函数。但是,LocationListener不响应。我已经尝试过调试以及在外面走动,以使onChangedLocation函数执行但没有任何反应。在调试LocationManager的requestLocationUpdates函数时会执行,但LocationListener永远不会执行。

locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 
    textView = (TextView) findViewById(R.id.textView); 
    textView2 = (TextView) findViewById(R.id.textView2); 
    locationListener = new myLocationListener(); 

    textView.setText("Longitude", TextView.BufferType.NORMAL); 
    textView2.setText("Latitude", TextView.BufferType.NORMAL); 

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locationListener); 

requestLocationUpdates

以上是使用requestLocationUpdates功能。

private class myLocationListener implements LocationListener { 
    @Override 
    public void onLocationChanged(Location location) { 
     //Log.e("Latitude: ", "" + location.getLatitude()); 
     //Log.e("Longitude: ", "" + location.getLongitude()); 
     if(location != null) 
     { 
      textView.setText(Double.toString(location.getLongitude()), TextView.BufferType.NORMAL); 
      textView2.setText(Double.toString(location.getLatitude()), TextView.BufferType.NORMAL); 
     } 
     else 
     { 
      textView.setText("No Location", TextView.BufferType.NORMAL); 
      textView2.setText("No Location", TextView.BufferType.NORMAL); 
     } 
     Toast.makeText(getApplicationContext(),"onLocationChanged Success",Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 

    } 

    @Override 
    public void onProviderEnabled(String provider) { 

    } 

    @Override 
    public void onProviderDisabled(String provider) { 
     Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
     startActivity(intent); 
    } 
} 

myLocationListener

这是myLocationListener实现LocationListener的。为了测试目的,我添加了一些额外的代码。吐司永远不会弹出,所以它看起来好像这个代码从未执行过。如果有人能帮助我,我会很感激。

谢谢!

新的问题:

在继续等待,我注意到它大约需要为位置服务真正开始工作一分钟的响应在这个页面开发后。所以,现在我的问题是:如何克服用户不得不等待使用应用程序的障碍?我见过使用基于位置的内容的应用程序,并且不需要那么长时间。我知道有getLastKnownLocation函数,但如果用户在再次打开应用程序之前行驶了50英里,该怎么办?任何帮助,将不胜感激。谢谢!

回答

1

每个为gps定位请求的设备都必须等到gps硬件变热。等待时间随设备而变化,并停留在哪里。如果您在建筑物内,这一次可能需要1分钟或更长时间。

为避免等待,您可以使用getLastKnownLocation方法,如果返回缓存的位置,请通过getTime方法检查位置的日期。确定你自己,这是你的场景旧位置?

如果位置太旧,您必须提出位置请求并等待。