有哪些替代onLocationChanged()方法的选择?

3
我正在使用API级别为10的Android和Google Maps,并通过telnet获取纬度和经度。
public void onLocationChanged(Location location) {
    lat = location.getLatitude();
    lng = location.getLongitude();
    //...
}

但用户需要先移动。还有其他解决方案吗?
1个回答

1

除了使用onLocationChanged(Location location)之外,另一种获取用户位置信息的方法是使用位置管理器和广播接收器。请参阅文档以了解有关位置管理器类的所有内容。使用位置管理器类,您将能够设置一个时间间隔,在此间隔内即使用户没有移动,也可以探测其位置。您将拥有:

LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

Intent intent = new Intent(context, LocationReceiver.class);
            pendingIntent = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);

            List<String> knownProviders = locationManager.getAllProviders();

            if(locationManager != null && pendingIntent != null && knownProviders.contains(LocationManager.GPS_PROVIDER)){
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MINUTE_INTERVAL*5, 0, pendingIntent);
            }

            if(locationManager != null && pendingIntent != null && knownProviders.contains(LocationManager.NETWORK_PROVIDER)){
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MINUTE_INTERVAL*5, 0, pendingIntent);
            }

在 LocationReceiver 类(Broadcast Receiver)中,您将拥有一个 onRecieve() 方法,在其中可以使用以下内容:
public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        location = (Location) bundle.get(LocationManager.KEY_LOCATION_CHANGED);

您可以使用该位置对象进行许多操作,请参考Android Location文档。


如果这解决了你的问题,那么你应该将答案标记为已接受。在投票计数下方的左边有一个勾号符号。 - Donnie

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接