2012-03-14 3 views
0

Im пытается получить текущее местоположение пользователя через GPS. Я прочитал документы Google по этому вопросу и попробовал несколько руководств, но ничего не работает должным образом. Вот мой код:GPS Locator не работает

public class useGPS extends Activity implements LocationListener 
{ 
private static final String TAG = "useGPS:"; 
LocationManager myLocManager; 
TextView locationData; 

@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.use_gps); 

    myLocManager = (LocationManager)this.getSystemService(LOCATION_SERVICE); 
    Location location = myLocManager.getLastKnownLocation(myLocManager.GPS_PROVIDER) ; 
    if(location != null) 
    { 
     Log.d(TAG,location.toString()); 
     Toast.makeText(this, "Location changed...", Toast.LENGTH_SHORT); 
     this.onLocationChanged(location); 
    } 
} 

@Override 
protected void onResume() 
{ 
    super.onResume(); 
    myLocManager.requestLocationUpdates(myLocManager.GPS_PROVIDER, 3000, 0, this); 

} 

@Override 
protected void onPause() 
{ 
    super.onPause(); 
    myLocManager.removeUpdates(this); 
} 


@Override 
public void onLocationChanged(Location location) 
{ 
    Log.d(TAG,"onLocationChanged with location: "+location.toString()); 

    // Return a string representation of the latitude & longitude. Pass it to the textview and update the text 
    String text = "Lat: "+location.getLatitude()+"\nLong: "+location.getLongitude(); 

    locationData = (TextView)findViewById(R.id.locationData); 
    locationData.setText(text); 
} 

@Override 
public void onProviderDisabled(String provider) { 
    Toast.makeText(getApplicationContext(), "Provider Disabled...", Toast.LENGTH_SHORT); 

} 

@Override 
public void onProviderEnabled(String provider) 
    { 
    Toast.makeText(getApplicationContext(), "Provider Enabled...", Toast.LENGTH_SHORT); 

} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 
    // TODO Auto-generated method stub 

} 

Я знаю, что GPS, как правило, не работает в закрытом помещении, так что я пошел и встал снаружи для 5minutes и это не делает разницы. Когда я использовал эмулятор для имитации местоположения, он вернул лат & долгое местоположение в порядке - никаких ошибок.

Кроме того - я включил необходимые разрешения в файле манифеста следующим образом:

<uses-permission android:name = "android.permission.ACCESS_FINE_LOCATION"></uses-permission> 

Любая идея относительно того, почему это не работает?

+1

вы проверили, например. Google Maps или какой-либо инструмент для тестирования GPS, что вы действительно получаете местоположение от GPS? На некоторых устройствах может потребоваться очень много времени. Возможно, GPS отключен. – zapl

+0

Определите действительно долго - я смотрел на устройство в течение 15 минут, и он ничего не делал, кроме спутникового изображения в верхней части экрана, анимации - вы знаете всю информацию о спутнике-отправке ... – Katana24

+1

GPS не имеет пока значок GPS не перестанет мигать. В зависимости от доступности местоположения/спутниковой видимости/доступности данных и т. Д. Long = 30 минут или около того. – zapl

ответ

0

Хорошо, поэтому я исправил проблему - я решил настроить код для создания слушателя вместо его реализации в классе. Я также гарантировал, что я вызвал как NETWORK_PROVIDER, так и GPS_PROVIDER на requestLocationUpdates для покрытия обеих баз. Вот пересмотренный код, обратите внимание, что закомментирована геокодирования часть врезается программы на данный момент, я не проработаны ошибки еще ...

public class useGPS extends Activity 
{ 
private static final String TAG = "useGPS:"; 

TextView locationData, addressData; 
LocationManager myLocManager; 
LocationListener locationListener; 

@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.use_gps); 

    // Acquire a reference to the system Location Manager 
    myLocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 

    // Define a listener that responds to location updates 
    locationListener = new LocationListener() 
    { 

     @Override 
     public void onLocationChanged(Location location) 
     { 
      // Return a string representation of the latitude & longitude. Pass it to the textview and update the text 
      String text = "Lat: "+location.getLatitude()+"\nLong: "+location.getLongitude(); 

      locationData = (TextView)findViewById(R.id.locationData); 
      locationData.setText(text); 
      /** 
      try 
      { 
       // Reverse Geocoding 
       Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault()); 
       List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(),0); 

       if(addresses != null) 
       { 
        // Get return address data 
        Address returnedAddress = addresses.get(0); 
        StringBuilder strReturnedAddress = new StringBuilder("Address:\n"); 

        for(int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) 
        { 
         // Return the address 
         strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n"); 
        } 
        // Set our textview to the address returned 
        addressData.setText(strReturnedAddress.toString()); 
       } else { 
        addressData.setText("Sorry, no address returned..."); 
       } 

      } catch(IOException e) 
      { 
       // Catch the Exception 
       e.printStackTrace(); 
       addressData.setText("Error: Cannot get Address!"); 
      } 
      */ 
     } 

     @Override 
     public void onProviderDisabled(String provider) 
     { 

     } 

     @Override 
     public void onProviderEnabled(String provider) 
     { 

     } 

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

     } 

    }; 

    // The two lines below request location updates from both GPS & the network location provider 
    myLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,locationListener); 
    myLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,locationListener); 
} 

@Override 
protected void onResume() 
{ 
    super.onResume(); 
    // The two lines below request location updates from both GPS & the network location provider 
    myLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,locationListener); 
    myLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,locationListener); 
} 

@Override 
protected void onPause() 
{ 
    super.onPause(); 
    // The two lines below request location updates from both GPS & the network location provider 
    myLocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,locationListener); 
    myLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,locationListener); 
} 

} 

Один последний момент - я не уверен, как этого момента, нужны ли мне два метода requestLocationUpdate для методов onResume() и onPause(). Метод onResume(), вероятно, будет изменен, чтобы получить последнее известное местоположение, если оно есть, вместо повторного установления метода обновления местоположений.

Надеюсь, что это поможет другим ...

Смежные вопросы