2013-12-10 67 views
0
public class WhereamI extends Activity { 

    @Override 
    public void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 
     setContentView(R.layout.activity_wheream_i); 

     LocationManager locationmanager; 
     String context = Context.LOCATION_SERVICE; 
     locationmanager = (LocationManager) getSystemService(context); 
     Criteria criteria = new Criteria(); 
     criteria.setAccuracy(Criteria.ACCURACY_FINE); 
     criteria.setAltitudeRequired(true); 
     criteria.setBearingRequired(false); 
     criteria.setCostAllowed(true); 
     criteria.setPowerRequirement(Criteria.POWER_LOW); 

     String provider = locationmanager.getBestProvider(criteria, true); 
     Location location = locationmanager.getLastKnownLocation(provider); 
     updatewithnewlocation(location); 
     locationmanager.requestLocationUpdates(provider, 2000, 10, 
       locationlistener); 
    } 

    private final LocationListener locationlistener = new LocationListener() { 

     private Location location; 

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

     @Override 
     public void onProviderEnabled(String arg0) { 
     } 

     @Override 
     public void onProviderDisabled(String arg0) { 
      updatewithnewlocation(null); 
     } 

     @Override 
     public void onLocationChanged(Location arg0) { 
      updatewithnewlocation(location); 
     } 
    }; 

    private void updatewithnewlocation(Location location) { 
     String latLongString; 
     TextView Text1; 
     Text1 = (TextView) findViewById(R.id.Text1); 
     if (location != null) { 
      double lat = location.getLatitude(); 
      double lng = location.getLongitude(); 
      double alt = location.getAltitude(); 
      latLongString = "Lat: " + lat + " Lon " + lng + " Altitude " 
        + alt + "feet"; 
     } else { 
      latLongString = "No Location Found: Sorry."; 
     } 
     Text1.setText("Your Current Position Is \n :" + latLongString); 
    } 

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

} 

我写了一个代码,通过GPS查找我的设备的当前位置。问题是设备大多数时间没有给出任何位置。但是,当我在代码中进行一些更改并将更改(或启动应用程序)上载到我的设备时,它会提供该位置。 这个应用程序的目的是找到位置的变化,并给予长期和纬度的价值,甚至altėude。我不知道该应用程序出了什么问题。有人可以吗?通过GPS寻找位置

+0

您并未检查是否打开了最佳位置提供程序。如果它关闭,那么你应该打开它,然后获得位置。 –

+0

最初,如果您从未使用过GPS或网络来获取您的位置,那么您将始终得到“找不到位置:对不起”。要获得一个位置,现在必须将2000和10设置为0,0否则,您将在20秒或5米位置更改后开始获取位置。 –

回答

0

无论您使用GPS,NETWORK还是最好的提供商,所有工作都基于从本地(设备)缓存中获取位置的相同原理。

试试这个实验。改变你的实际位置(移动,距离你现在的位置约200米)并加载谷歌地图,突然你的应用程序也会返回正确的坐标。这是因为谷歌地图知道如何触发本地缓存更新。在您启动应用程序之后它为您提供位置的原因是因为您在代码中使用requestLocationUpdate触发本地缓存。因此,它给你的坐标,直到它得到一个新的。

+0

请接受并关闭该问题是否对您有帮助 – user2511882