2012-10-16 225 views
2

我想目前的经度和纬度为INT无法获取当前位置坐标

所以我用这个代码

 locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
     locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 
       0, this); 

     Location location = locationManager 
       .getLastKnownLocation(LocationManager.GPS_PROVIDER); 


     try { 
      gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
     } catch (Exception ex) { 
     } 
     try { 
      network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
     } catch (Exception ex) { 
     } 

     // don't start listeners if no provider is enabled 
     if (!gps_enabled && !network_enabled) { 
       ....Notify 
     } 

     if (gps_enabled) { 
      if (location != null) { 
       longitude =(int) (location.getLongitude()*1e6); 
       latitude = (int) (location.getLatitude()*1e6); 
String accuracy = "Accuracy: " + location.getAccuracy(); 
      } 
     } 
     if (network_enabled) { 
      if (location != null) { 

       longitude =(int) (location.getLongitude()*1e6); 
       latitude = (int) (location.getLatitude()*1e6); 
       String accuracy = "Accuracy: " + location.getAccuracy(); 
      } 
      } 

     locationManager.removeUpdates(this); 

不幸的是经度和纬度总是空。

我拥有清单中所需的所有权限。

我该如何解决这个问题?

+0

您在模拟器或真实设备检查? – Syn3sthete

+0

在模拟器中它不能显示它只能在真实的设计中使用 –

+1

http://stackoverflow.com/questions/3145089/what-is-the-simplest-and-most-robust-way-to-get-the-users-current -location-in-a –

回答

1

嗯,这是我使用的位置监听器现在

import android.content.Context; 
import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 

public class LocationUtils implements LocationListener{ 

Context context; 
private String provider; 
private LocationManager locationManager; 
private String latitude="no value"; 
private String longitude="no value"; 
public LocationUtils(Context context) { 
    this.context=context; 
    // Get the location manager 
     locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
     // Define the criteria how to select the locatioin provider -> use 
     // default 
     latitude="no value"; 
     longitude="no value"; 
     Criteria criteria = new Criteria(); 
     provider = locationManager.getBestProvider(criteria, false); 
     Location location = locationManager.getLastKnownLocation(provider); 

     // Initialize the location fields 
     if (location != null) { 
      /*Toast.makeText(context, "Provider " + provider + " has been selected.", 
        Toast.LENGTH_SHORT).show();*/ 
     // System.out.println("Provider " + provider + " has been selected."); 
      onLocationChanged(location); 
     } else { 
      /*Toast.makeText(context, "Location not available", 
        Toast.LENGTH_SHORT).show();*/ 
     } 
} 


@Override 
public void onLocationChanged(Location location) { 
    double lat = (double) (location.getLatitude()); 
    double lng = (double) (location.getLongitude()); 
    latitude = lat + ""; 
    longitude = lng + ""; 
    /* Toast.makeText(context, " lat: "+lat +" Long:"+lng, 
      Toast.LENGTH_SHORT).show(); */ 
} 

@Override 
public void onProviderDisabled(String provider) { 
    //Toast.makeText(context, "Disabled provider " + provider, 
     //  Toast.LENGTH_SHORT).show();  
} 

@Override 
public void onProviderEnabled(String provider) { 
    //Toast.makeText(context, "Enabled new provider " + provider, 
     //  Toast.LENGTH_SHORT).show(); 
} 

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

} 
public String getLatitude() { 
    return latitude; 
} 

public String getLongitude() { 
    return longitude; 
} 


} 

在您的活动u能得到

LocationUtils appLocationManager = new LocationUtils(getContext()); 
String latitude = appLocationManager.getLatitude(); 
String longitude = appLocationManager.getLongitude(); 

另外补充

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission> 
in your manifest file 
+0

wats这个解决方案错了吗? –

0

试试这个代码

 double longitude,latitude; 
     int lon,lat; 

     getcurrentloc.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){ 
       Toast.makeText(GpsLocationFinder.this, "Enable Your GPS", Toast.LENGTH_LONG).show(); 
      }else{ 
      LocationResult locationResult=new LocationResult() {  
       @Override 
       public void gotLocation(Location location) { 
        // TODO Auto-generated method stub 


         longitude=location.getLongitude(); 
         latitude=location.getLatitude(); 
         lon=(int)longitude;  
         lat=(int)latitude; 
         Toast.makeText(GpsLocationFinder.this, "Current Longitude"+longitude+" Current Latitude"+latitude,Toast.LENGTH_LONG).show(); 

       } 

      };  
      MyLocation myLocation = new MyLocation(); 
      myLocation.getLocation(GpsLocationFinder.this, locationResult);   


      } 

     } 
    }); 

而且MyLocation类如下

 public class MyLocation { 
Timer timer1; 
LocationManager lm; 
LocationResult locationResult; 
boolean gps_enabled=false; 
boolean network_enabled=false; 
double longitude,latitude; 

public boolean getLocation(Context context, LocationResult result) 
{ 
    //I use LocationResult callback class to pass location value from MyLocation to user code. 


     //Log.e("GPS DISTANCE","GPS Enabled"); 
    locationResult=result; 
    if(lm==null) 
     lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 

    //exceptions will be thrown if provider is not permitted. 

    //don't start listeners if no provider is enabled 

     //try{ 

     try{ 

      gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER); 

      }catch(Exception ex){ 

      } 
     try{ 
      network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
     }catch(Exception ex){ 

     } 
     if(!gps_enabled && !network_enabled){ 
      return false; 
     } 

    if(gps_enabled){ 

     lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 100, locationListenerGps); 
    } 
    if(network_enabled) 
     lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork); 
    timer1=new Timer(); 
    timer1.schedule(new GetLastLocation(), 30000);   
    return true; 

} 


LocationListener locationListenerGps = new LocationListener() { 
    public void onLocationChanged(Location location) { 
     timer1.cancel(); 
     locationResult.gotLocation(location); 
     lm.removeUpdates(this); 
     lm.removeUpdates(locationListenerNetwork); 
    } 
    public void onProviderDisabled(String provider) {} 
    public void onProviderEnabled(String provider) {} 
    public void onStatusChanged(String provider, int status, Bundle extras) {} 
}; 

LocationListener locationListenerNetwork = new LocationListener() { 
    public void onLocationChanged(Location location) { 
     timer1.cancel(); 
     locationResult.gotLocation(location); 
     lm.removeUpdates(this); 
     lm.removeUpdates(locationListenerGps); 
    } 
    public void onProviderDisabled(String provider) { 

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


class GetLastLocation extends TimerTask { 
    @Override 
    public void run() { 
     lm.removeUpdates(locationListenerGps); 
     lm.removeUpdates(locationListenerNetwork); 

     Location net_loc=null, gps_loc=null; 
     if(gps_enabled) 
      gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
     if(network_enabled) 
      net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 

     //if there are both values use the latest one 
     if(gps_loc!=null && net_loc!=null){ 
      if(gps_loc.getTime()>net_loc.getTime()) 
       locationResult.gotLocation(gps_loc); 
      else 
       locationResult.gotLocation(net_loc); 
      return; 
     } 

     if(gps_loc!=null){ 
      locationResult.gotLocation(gps_loc); 
      return; 
     } 
     if(net_loc!=null){ 
      locationResult.gotLocation(net_loc); 
      return; 
     } 
     locationResult.gotLocation(null); 
    } 
} 

public static abstract class LocationResult{ 
    public abstract void gotLocation(Location location); 
} 
    } 
0
  1. 首先检查您的设备支持GPS。列入清单
  2. 检查所有权限您正在使用GPS提供商,以便删除该行并分别获取位置都提供者(应该有可能是您的GPS不可用在获取最后已知位置那么你没有得到位置,并且你正在使用GPS获取最后一个已知的位置,所以它可以为空,如果位置为空,那么它将不会像if(network_enabled)if(gps_enabled)这样的条件内)。

总之,检查GPS的最后已知位置,如果它为空,则尝试使用位置提供程序获取位置并使用该位置。

0
public class SMS_Service extends Service { 

private final String LOGTAG = "SMS_Service"; 

String latLongString; 
String addressString; 
double altitude; 
int LAC; 
int mcc = 0; 
int mnc = 0; 
String pn_no; 
Altitude_Details ld = new Altitude_Details(); 

@Override 
public IBinder onBind(Intent intent) { 
    // TODO Auto-generated method stub 
    return null; 
} 

@Override 
public void onCreate() { 
    // TODO Auto-generated method stub 
    super.onCreate(); 
    Log.e(LOGTAG, "created"); 
} 

@Override 
public void onDestroy() { 
    // TODO Auto-generated method stub 
    super.onDestroy(); 
    Log.e(LOGTAG, "destroyed"); 
} 

@Override 
public void onStart(Intent intent, int startId) { 
    // TODO Auto-generated method stub 
    super.onStart(intent, startId); 
    Log.e(LOGTAG, "started"); 

    SmsManager sms = SmsManager.getDefault(); 
    // get phone number from shared preference 
    SharedPreferences default1 = getSharedPreferences("Device", 
      MODE_WORLD_WRITEABLE); 
    pn_no = default1.getString("Phone_NO", ""); 
    Log.e("phone_no in sms service", pn_no); 

    String From = intent.getStringExtra("From"); 
    String Msg = intent.getStringExtra("Msg"); // get message from intent 
    Log.e("ON start:", "" + From); 
    Log.e("ON start:", "" + Msg); 

    String number = From.substring(7, 11); 
    Log.e("ON start: SUBSTRING", "" + number); 

    // check msg for Location keyword match or not 
    if (Msg.equals("LOCATION") && pn_no.equals(number)) { 
     Log.e("location:", "Location found"); 

     TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); 
     String networkOperator = tel.getNetworkOperator(); 

     // find MNC and MCC 
     if (networkOperator != null) { 
      mcc = Integer.parseInt(networkOperator.substring(0, 3)); 
      mnc = Integer.parseInt(networkOperator.substring(3)); 
      Log.e("MCC", "" + mcc); 
      Log.e("MNC", "" + mnc); 
     } 

     // find LAC for GSM 
     if (tel.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) { 
      final GsmCellLocation location = (GsmCellLocation) tel 
        .getCellLocation(); 
      if (location != null) { 
       LAC = location.getLac(); 
       Log.e("cell location", "LAC: " + location.getLac() 
         + " CID: " + location.getCid()); 
      } 
     } 

     LocationManager locationManager; 
     String context = Context.LOCATION_SERVICE; 
     locationManager = (LocationManager) getSystemService(context); 
     String provider = LocationManager.GPS_PROVIDER; 
     Location location = locationManager.getLastKnownLocation(provider); 

     // update method return latest location 
     updateWithNewLocation(location); 

     // location change then listner called 
     locationManager.requestLocationUpdates(provider, 2000, 10, 
       locationListener); 

     // send mcc,mnc,latitude,longitude,altitude,address,Link in message 
     String Url = "http://itouchmap.com/latlong.html"; 

     sms.sendTextMessage(pn_no, null, "\nLocation:\n" + "MCC: " + mcc 
       + "\nMNC: " + mnc + "\nLAC:" + LAC + latLongString 
       + "\nAltitude:" + altitude + "feet" 
       + "\nGo to Below site:\n" + Url, null, null); 

     sms.sendTextMessage(pn_no, null, "\nAddress:\n" + addressString, 
       null, null); 

     // stop service automatically 
     SMS_Service.this.stopSelf(); 
    } 

    else { 
     Log.e("loation:", "Location not found"); 
     SMS_Service.this.stopSelf(); 
    } 
} 

private final LocationListener locationListener = new LocationListener() { 

    public void onLocationChanged(Location location) { 
     updateWithNewLocation(location); 

    } 

    public void onProviderDisabled(String provider) { 
     updateWithNewLocation(null); 

    } 

    public void onProviderEnabled(String provider) { 
    } 

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

private void updateWithNewLocation(Location location) { 
    // TODO Auto-generated method stub 

    addressString = "\nno address found"; 
    // check location get or not from provider 
    if (location != null) { 

     // get latitude and longitude 
     double latitude = location.getLatitude(); 
     double longitude = location.getLongitude(); 

     latLongString = "\nLat:" + latitude + "\nLong:" + longitude; 
     Log.e("location", "" + latLongString); 

     // get altitude from method 
     altitude = ld.getElevationFromGoogleMaps(latitude, longitude); 
     Log.e("Altitude", "" + altitude); 

     // find address from latitude and longitude 
     Geocoder gc = new Geocoder(this, Locale.getDefault()); 

     try { 
      List<Address> addresses = gc.getFromLocation(latitude, 
        longitude, 1); 
      StringBuilder sb = new StringBuilder(); 
      if (addresses.size() > 0) { 
       Address address = addresses.get(0); 
       for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) 

        sb.append(address.getAddressLine(i)).append("\n"); 
      } 
      addressString = sb.toString(); 
      Log.e("Address", "" + addressString); 
     } catch (IOException e) { 
     } 

    } else { 
     latLongString = "\n No location found"; 
     Log.e("location", "" + latLongString); 
      } 
    } 
} 

嘿,你可以做服务,并使用此代码来获取海拔和纬度和解码此使用类