Android获取当前位置的最佳方式

8

如下情况下,在安卓设备上获取当前位置的最佳方式是什么:

  1. 如果GPS不可用,则从网络提供商获取位置。

  2. 如果GPS可用且可以获得当前位置,则从GPS提供商获取位置。

  3. 如果GPS可用但无法获取当前位置(即持续搜索位置),则从网络提供商获取位置。

    现在,如果GPS不可用,我可以从网络获取位置,非常感谢提供最佳答案。


3
请查看这个库:https://code.google.com/p/little-fluffy-location-library/ - dannyroa
你有没有检查旧的帖子
  1. https://dev59.com/UHI_5IYBdhLWcg3wJPZu
  2. https://dev59.com/QnA75IYBdhLWcg3wuLjD#3145655
- surhidamatya
最简单的方法是使用一个高级库,就像这个:https://github.com/delight-im/Android-SimpleLocation - caw
3个回答

3

好的,你可以使用TimerTimerTask类。

LocationManager manager;
TimerTask mTimertask;
GPSLocationListener mGPSLocationListener;
int i = 0; //Here i works as counter;
private static final int MAX_ATTEMPTS = 250;

public void getCurrentLocation() {
    manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    mGPSLocationListener = new GPSLocationListener();

    manager.addGpsStatusListener(mGPSStatusListener);
    mTimerTask = new LocTimerTask(LocationManager.GPS_PROVIDER);

    if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        Log.v(TAG, "GPS ENABLED");
        manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,
                50.0f, mGPSLocationListener);
    } else {
        turnGPSOn();
        manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,
                50.0f, mGPSLocationListener);
    }
    
    if(manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L,
                50.0f, mNetworkLocationListener);
    }

    if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        Log.v(TAG, "GPS ENABLED");
        manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                1000L, 50.0f, mGPSLocationListener);
    }

    myLocTimer = new Timer("LocationRunner", true);
    myLocTimer.schedule(mTimerTask, 0, 500);
}

GPSStatusListener

private GpsStatus.Listener mGPSStatusListener = new GpsStatus.Listener() {

    @Override
    public synchronized void onGpsStatusChanged(int event) {
        switch (event) {
        case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
            Log.v(TAG, "GPS SAtellitestatus");
            GpsStatus status = manager.getGpsStatus(null);
            mSattelites = 0;
            Iterable<GpsSatellite> list = status.getSatellites();
            for (GpsSatellite satellite : list) {
                if (satellite.usedInFix()) {
                    mSattelites++;
                }
            }
            break;

        case GpsStatus.GPS_EVENT_FIRST_FIX:
            /*
             * Toast.makeText(getApplicationContext(), "Got First Fix",
             * Toast.LENGTH_LONG).show();
             */
            break;

        case GpsStatus.GPS_EVENT_STARTED:
            /*
             * Toast.makeText(getApplicationContext(), "GPS Event Started",
             * Toast.LENGTH_LONG).show();
             */
            break;

        case GpsStatus.GPS_EVENT_STOPPED:
            /*
             * Toast.makeText(getApplicationContext(), "GPS Event Stopped",
             * Toast.LENGTH_LONG).show();
             */
            break;
        default:
            break;
        }
    }
};

LocationListener

public class GPSLocationListener implements LocationListener {

    @Override
    public void onLocationChanged(Location argLocation) {
        location = argLocation;
    }

    public void onProviderDisabled(String provider) {

    }

    public void onProviderEnabled(String provider) {

    }

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

    }
}

计时器任务类
class LocTimerTask extends TimerTask {
    String provider;

    public LocTimerTask(String provider) {
        this.provider = provider;
    }

    final Handler mHandler = new Handler(Looper.getMainLooper());

    Runnable r = new Runnable() {
        @Override
        public void run() {
            i++;
            Log.v(TAG, "Timer Task run" + i);
            location = manager.getLastKnownLocation(provider);

            if (location != null) {
                Log.v(TAG, "in timer task run in if location not null");
                isGPS = true;
                onLocationReceived(location);
                myLocTimer.cancel();
                myLocTimer.purge();
                mTimerTask.cancel();
                return;
            } else {
                Log.v(TAG, "in timer task run in else location null");
                isGPS = false;
                if (location == null && i == MAX_ATTEMPTS) {
                    Log.v(TAG, "if 1 max attempts done");
                    turnGPSOff();
                    location = manager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        Log.v(TAG,
                                "if 1 max attempts done Location from network not null");
                        Log.v(TAG,
                                "if 1 max attempts done Location from network not null coordinates not null");
                        onLocationReceived(location);
                        myLocTimer.cancel();
                        myLocTimer.purge();
                        mTimerTask.cancel();
                        return;
                    }
                } else {
                    return;
                }
            }
            i = 0;
        }
    };

    public void run() {
        mHandler.post(r);
    }
}

在这里,计时器已被安排在每500毫秒运行一次。这意味着,在每500毫秒计时器任务的run方法将被执行。在运行方法中,尝试从GPS提供程序获取特定数量(这里是MAX_ATTEMPTS)的位置。如果在指定次数内获取到位置,则使用该位置;否则,如果计数器(这里是i)的值超过了MAX_ATTEMPTS,则从网络提供程序获取位置。获取位置后,我将该位置传递给回调方法onLocationReceived(Location mLoc),您可以在其中使用位置数据进行进一步的工作。以下是如何使用回调方法的方式:

监听器

public interface OnLocationReceivedListener {
public void onLocationReceived(Location mLoc); //callback method which will be defined in your class.

你的类应该实现上述定义的监听器。在你的类中:

@Override
public void onLocationReceived(Location mLoc) {
    //Do your stuff
}

希望它有所帮助。如果有更好的方法,请告诉我。


0
If GPS is available and can get current location, 

对于上述问题,您可以尝试以下方法:

使用此方法,您可以获取当前位置的纬度和经度,然后将该值传递给获取地图的函数。

public class MyLocationListener implements LocationListener

{

@Override

public void onLocationChanged(Location loc)

{

loc.getLatitude();

loc.getLongitude();

String Text = “My current location is: “ +

“Latitud = “ + loc.getLatitude() +

“Longitud = “ + loc.getLongitude();

Toast.makeText( getApplicationContext(),

Text,

Toast.LENGTH_SHORT).show();

}

@Override

public void onProviderDisabled(String provider)

{

Toast.makeText( getApplicationContext(),

“Gps Disabled”,

Toast.LENGTH_SHORT ).show();

}

@Override

public void onProviderEnabled(String provider)

{

Toast.makeText( getApplicationContext(),

“Gps Enabled”,

Toast.LENGTH_SHORT).show();

}

@Override

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

{

}

}

}

0

类成员 boolean mIsGpsFix;

请求 GPS 位置更新并设置倒计时器。

mCountDown.start();

private CountDownTimer mCountDown = new CountDownTimer(time to wait for Gps fix, same as right)
{

    @Override
    public void onTick(long millisUntilFinished)
    {

    }

    @Override
    public void onFinish()
    {
        // No fix after the desire amount of time collapse
        if (!mIsGpsFix)
        // Register for Network
    }
};

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