如何在后台线程中启动GPS定位?

时间:2012-01-07 10:38:47

标签: android android-location

我需要在单独的线程中使用GPS检索当前位置。

3 个答案:

答案 0 :(得分:1)

研究以下代码,

public class LocListener implements LocationListener {
    private static double lat =0.0;
    private static double lon = 0.0;
    private static double alt = 0.0; 
    private static double speed = 0.0;

    public static double getLat()
    {
        return lat;
    }

    public static double getLon() 
    {
        return lon;
    }

    public static double getAlt()
    {
        return alt;
    }

    public static double getSpeed()
    {
        return speed;
    }

    @Override
    public void onLocationChanged(Location location) 
    {
        lat = location.getLatitude();
        lon = location.getLongitude();
        alt = location.getAltitude();
        speed = location.getSpeed(); 
    }

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

现在使用此代码在线程中启动gps。

new Thread ( new Runnable()
{
     public void run()
     {
        locationManager = ( LocationManager ) getSystemService ( Context.LOCATION_SERVICE );
            locationListener = new LocListener();
            locationManager.requestLocationUpdates ( LocationManager.GPS_PROVIDER, 0, 0, locationListener );
     }
}).start();

答案 1 :(得分:0)

GPS异步工作,您不需要在单独的线程中调用,GPS在获取位置时不会冻结用户界面。最好的是你可以使用progressDialog并在获得职位后解除progressDialog。

答案 2 :(得分:0)

private void turnGPSOn(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(!provider.contains("gps")){ //if gps is disabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}

private void turnGPSOff(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if(provider.contains("gps")){ //if gps is enabled
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3")); 
        sendBroadcast(poke);
    }
}