2013-03-02 2 views
0

Я сделал простую программу для извлечения местоположения, сначала неожиданно меня закрыл, и я изменил код, и теперь он не закрывается, но в моих двух редактах, где я должен получить свою широту и долготу, он остается пустым мой код, как показано ниже ... имеет два класса 1) mainactivity.java и 2) GPSTracker.javaполучение местоположения в приложении android

mainactiviy.java

public class MainActivity extends Activity { 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    final Button gpsButton = (Button) findViewById(R.id.getloc); 

    gpsButton.setOnClickListener(new Button.OnClickListener() { 
    public void onClick(View v){ 
     LoadCoords(); 
    }}); 


} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    return true; 
} 

public void LoadCoords(){ 
    EditText locn = (EditText)findViewById(R.id.text1); 
    EditText locn1 = (EditText)findViewById(R.id.text2); 
    GPSTracker gps = new GPSTracker(this); 
    if(gps.canGetLocation){ 
    Double latPoint=gps.getLatitude(); 
    Double lngPoint =gps.getLongitude(); 

    locn.setText(latPoint.toString()); 
    locn1.setText(lngPoint.toString()); 
} 
} 
} 

GPSTracker.java

public class GPSTracker extends Service implements LocationListener{ 
private final Context mContext; 

// flag for GPS status 
boolean isGPSEnabled = false; 

// flag for network status 
boolean isNetworkEnabled = false; 

boolean canGetLocation = false; 

Location location; // location 
double latitude; // latitude 
double longitude; // longitude 

// The minimum distance to change Updates in meters 
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters 

// The minimum time between updates in milliseconds 
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute 

// Declaring a Location Manager 
protected LocationManager locationManager; 

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

     // getting GPS status 
     isGPSEnabled = locationManager 
       .isProviderEnabled(LocationManager.GPS_PROVIDER); 

     // getting network status 
     isNetworkEnabled = locationManager 
       .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (!isGPSEnabled && !isNetworkEnabled) { 
      // no network provider is enabled 
     } else { 
      this.canGetLocation = true; 
      // First get location from Network Provider 
      if (isNetworkEnabled) { 
       locationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       Log.d("Network", "Network"); 
       if (locationManager != null) { 
        location = locationManager 
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (location != null) { 
         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 
        } 
       } 
      } 
      // if GPS Enabled get lat/long using GPS Services 
      if (isGPSEnabled) { 
       if (location == null) { 
        locationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("GPS Enabled", "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 double getLatitude(){ 
    if(location != null){ 
     latitude = location.getLatitude(); 
    } 

    // return latitude 
    return latitude; 
} 

/** 
* Function to get longitude 
* */ 
public double getLongitude(){ 
    if(location != null){ 
     longitude = location.getLongitude(); 
    } 

    // return longitude 
    return longitude; 
} 
@Override 
public void onLocationChanged(Location location) { 
} 

@Override 
public void onProviderDisabled(String provider) { 
} 

@Override 
public void onProviderEnabled(String provider) { 
} 

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

@Override 
public IBinder onBind(Intent arg0) { 
    return null; 
} 
} 

мой main.xml как ниже

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools" 
android:layout_width="match_parent" 
android:layout_height="match_parent" > 

<TableRow android:layout_width="fill_parent" > 
<EditText 
android:id="@+id/text1" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:layout_alignParentLeft="true" 
android:layout_alignParentRight="true" 
android:layout_alignParentTop="true" 
android:ems="10" > 

<requestFocus /> 
</EditText> 
</TableRow> 
<TableRow > 
<EditText 
android:id="@+id/text2" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:layout_alignParentLeft="true" 
android:layout_alignParentRight="true" 
android:layout_alignParentTop="true" 
android:ems="10" > 
</EditText> 
</TableRow> 
<TableRow 
android:id="@+id/tableRow1" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" > 
<Button 
android:id="@+id/getloc" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:text="Get Location" /> 
</TableRow> 
</TableLayout> 
+0

Вы добавили требуемые разрешения на манифест? Также эмулятор вернет null в качестве последнего известного местоположения. Используйте это для запуска AVD: ADB -e эму гео исправить 50 50 – Iraklis

+0

я использовал ниже разрешений –

+0

<использует-разрешение андроида: Name = "android.permission.ACCESS_GPS"> \t \t <использование -permission андроид: имя = "android.permission.ACCESS_LOCATION"> \t \t <использует-разрешение андроида: имя = "android.permission.ACCESS_FINE_LOCATION" /> –

ответ

1

Вы должны работать с андроид устройства для приложений определения местоположения это своего рода осложненной эмулятор также попробовать этот код это дает вам местоположение или от GPS или сети провайдера в зависимости от того доступен ,

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

      // getting GPS status 
      isGPSEnabled = locationManager 
        .isProviderEnabled(LocationManager.GPS_PROVIDER); 

      // getting network status 
      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 GPS Enabled get lat/long using GPS Services 
       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; 
    } 
+0

вы можете сказать мне, что не так с приведенным выше кодом –

+0

ваш объект местоположения возвращает null на эмуляторе, по этой причине вы столкнулись с этой ошибкой. Location location = myManager.getLastKnownLocation (поставщик); –

+0

Попробуйте этот код, он работает даже на эмуляторе, вам нужно запустить gps из элемента управления эмулятора в ddms –

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