GPS的Andr​​oid - 获得定位只有一次 [英] GPS Android - get positioning only once

查看:113
本文介绍了GPS的Andr​​oid - 获得定位只有一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法来访问GPS,而不是曾经有一个活套的不断检查位置更新?

Is there a way to access the GPS once instead of having a looper that constantly checks for location updates?

在我的方案中所有我感兴趣的是找到当前坐标,而不是与GPS卫星的持续连接。没有人有任何想法如何可以做到这一点?提前致谢。

In my scenario all I'm interested in is finding the current co-ordinates and not a continuous connection with the GPS satellite. Does anyone have any ideas how this can be done? Thanks in advance.

推荐答案

首先检查是否最后一个已知位置是最近的事。如果不是这样,我相信你一定要设置onLocationChanged监听器,但一旦你得到你的第一个有效的位置,你可以随时停止更新的数据流。

First check if the last know location is recent. If not, I believe you must to set up onLocationChanged listener, but once you get your first valid location you can always stop the stream of updates.

添加

public class Example extends Activity implements LocationListener {
    LocationManager mLocationManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(location != null && location.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) {
            // Do something with the recent location fix
            //  otherwise wait for the update below
        }
        else {
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
        }
    }

    public void onLocationChanged(Location location) {
        if (location != null) {
            Log.v("Location Changed", location.getLatitude() + " and " + location.getLongitude());
            mLocationManager.removeUpdates(this);
        }
    }

    // Required functions    
    public void onProviderDisabled(String arg0) {}
    public void onProviderEnabled(String arg0) {}
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
}

这篇关于GPS的Andr​​oid - 获得定位只有一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆