我在我的测试人员的一部手机上获取用户位置时遇到了问题。它对我来说总是很好,所以我不知道有什么区别。
顺序如下:
1:重启他的手机。 2. 检查以确保启用定位服务(针对 GPS 和网络)。 3. 启动我的应用程序。
操作系统从不提供有效位置。 getLastKnownLocation() 始终为 GPS_PROVIDER 和 NETWORK_PROVIDER 返回 null,并且在请求 LocatioUpdates 后永远不会调用 LocationListener。
- 然后他运行 Google map 应用(似乎确实找到了他)。
- 然后,如果他再次运行我的应用程序并且它确实获得了正确的位置。
这是我的代码的基础:
LocationManager locationManager = (LocationManager) this.getSystemService( Context.LOCATION_SERVICE );
LocationListener locationListener = new LocationListener()
{
public void onLocationChanged( Location location )
{
useLocation( location );
}
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
// Checks a minimum of every 120 seconds. Location must change by 10000 meters
String provider = locationManager.getBestProvider( new Criteria(), true );
if ( provider != null )
{
System.out.println( "Using provider: " + provider );
locationManager.requestLocationUpdates( provider, 120 * 1000, 10000, locationListener );
}
// Get the last know location for immediate use
Location lastLocation = locationManager.getLastKnownLocation( LocationManager.GPS_PROVIDER );
if ( lastLocation != null )
useLocation( lastLocation );
else
useLocation( locationManager.getLastKnownLocation( LocationManager.NETWORK_PROVIDER ) );
当它失败时,代码会说最好的提供者是“网络”,所以这就是我使用的。但是永远不会调用 onLocationChanged。我也从未从 getLastKnowLocation() 获得非空值。
我需要做一些进一步的魔法才能让它在重启后始终如一地工作吗?
最佳答案
我假设您已经在服务中编写了它。如果是这种情况,请尝试使用监听启动事件的 BroadCastReciever。例如
<receiver android:name="com.singulera.familysiren.receiver.BootReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED">
</action>
<category android:name="android.intent.category.HOME">
</category>
</intent-filter>
</receiver>
然后在 BootReceiver 文件中调用你的服务。
关于Android 手机重启后无法获取位置信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5379356/