2015-04-14 5 views
0

Я только начинаю изучать андроид. У меня есть активность ящика навигации. Я пытаюсь получить свое текущее местоположение. Это мой код:Получить текущее местоположение в статическом контексте

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
           Bundle savedInstanceState) { 

      View rootView=inflater.inflate(R.layout.fragment_main, container, false); 
       int sectionNumber = getArguments().getInt(ARG_SECTION_NUMBER); 
       switch (sectionNumber) { 
        case 1: 
         rootView = inflater.inflate(R.layout.fragment_monitor, container, false); 
         TextView lat = (TextView) rootView.findViewById(R.id.lat); 
         LocationManager locationmanager; 
         String context=Context.LOCATION_SERVICE; 
         locationmanager=(LocationManager) getSystemService(context); 
         String provider=LocationManager.NETWORK_PROVIDER; 
         Location location= locationmanager.getLastKnownLocation(provider); 

         double lat = location.getLatitude(); 
         double lon = location.getLongitude(); 

         break; 
        case 2: 
         rootView = inflater.inflate(R.layout.activity_mapa, container, false); 
         break; 
        case 3: 
         break; 
        default: 
         rootView = inflater.inflate(R.layout.fragment_main, container, false); 
       } 
      return rootView; 
     } 

У него есть ошибка в методе getSystemService(). В нем говорится, что нестатический метод не может ссылаться на статический контекст.

Кто-нибудь знает, как это решить?

спасибо.

ответ

1

попробовать это:

LocationManager locationManager = (LocationManager) getActivity() 
      .getSystemService(Context.LOCATION_SERVICE); 
      ` 

быть в курсе, что ваш текущий код будет дает исключение нулевого указателя, если последнее известное местоположение является нулевым, так обращаться, что я советую вам чтобы сделать, если заявление справиться с этой ситуацией

if(location!=null){ 
//your code 
    }else{ 
GPSTracker d=new GPSTracker(getActivity()); 
      //to get lat and lng use d.getLatitude and d.getLongitude 
} 

GPSTracker Класс:

public class GPSTracker implements LocationListener { 
private final Context mContext; 
boolean isGPSEnabled = false; 
boolean isNetworkEnabled = false; 
boolean canGetLocation = false; 
Location location = null; 
double latitude; 
double longitude; 

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters 
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute 

protected LocationManager locationManager; 
private Location m_Location; 
public GPSTracker(Context context) { 
    this.mContext = context; 
    m_Location = getLocation(); 
    System.out.println("location Latitude:"+m_Location.getLatitude()); 
    System.out.println("location Longitude:"+m_Location.getLongitude()); 
    System.out.println("getLocation():"+getLocation()); 
    } 

public Location getLocation() { 
    try { 
     locationManager = (LocationManager) mContext 
       .getSystemService(Context.LOCATION_SERVICE); 

     isGPSEnabled = locationManager 
       .isProviderEnabled(LocationManager.GPS_PROVIDER); 

     isNetworkEnabled = locationManager 
       .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (!isGPSEnabled && !isNetworkEnabled) { 
      // no network provider is enabled 
     } 
     else { 
      this.canGetLocation = true; 
      if (isNetworkEnabled) { 
       locationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       Log.d("Network", "Network Enabled"); 
       if (locationManager != null) { 
        location = locationManager 
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (location != null) { 
         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 
        } 
       } 
      } 
      if (isGPSEnabled) { 
       if (location == null) { 
        locationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("GPS", "GPS Enabled"); 
        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
      } 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return location; 
} 

public void stopUsingGPS() { 
    if (locationManager != null) { 
     locationManager.removeUpdates(GPSTracker.this); 
    } 
} 

public double getLatitude() { 
    if (location != null) { 
     latitude = location.getLatitude(); 
    } 

    return latitude; 
} 

public double getLongitude() { 
    if (location != null) { 
     longitude = location.getLongitude(); 
    } 

    return longitude; 
} 

public boolean canGetLocation() { 
    return this.canGetLocation; 
} 

@Override 
public void onLocationChanged(Location arg0) { 
    // TODO Auto-generated method stub 

} 

@Override 
public void onProviderDisabled(String arg0) { 
    // TODO Auto-generated method stub 

} 

@Override 
public void onProviderEnabled(String arg0) { 
    // TODO Auto-generated method stub 

} 

@Override 
public void onStatusChanged(String arg0, int arg1, Bundle arg2) { 
    // TODO Auto-generated method stub 

} 


} 

надеюсь, что это вам поможет.

+0

Все прошло отлично! Спасибо! – MCGBra

+0

И спасибо вам за класс GPSTracker! Я уверен, что это будет полезно во многих проектах! – MCGBra

+0

NP рад, что я мог бы помочь :) –

3

getSystemService, является методом Context.

locationmanager=(LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE); 

следует помнить, что getLastKnownLocation возвращает нулевое значение, если положение не было приобретено до сих пор. Таким образом, вы, вероятно, хотите, чтобы проверить на несуществующий объект

+0

Все прошло отлично! Спасибо! – MCGBra

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