2016-07-22 39 views
0

我想获取经度和纬度的当前位置坐标。这是我到目前为止的代码:在android中获取当前位置(坐标)?

public class MainActivity extends AppCompatActivity { 

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

    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 
    MyLocationListener myLocationListener = new MyLocationListener(); 
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     return; 
    } 
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, myLocationListener); 

} 

}

这个类太:

public class MyLocationListener implements LocationListener { 
private static final String TAG = "COORDINATES: "; 

@Override 
public void onLocationChanged(Location location) { 
    if(location != null){ 
     Log.e(TAG, "Latitude: " + location.getLatitude()); 
     Log.e(TAG, "Longitude: " + location.getLongitude()); 
    } 
} 

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

} 

@Override 
public void onProviderEnabled(String provider) { 

} 

@Override 
public void onProviderDisabled(String provider) { 

} 

}

当我运行在模拟器的应用程序,我没有得到任何带坐标的日志消息。有什么建议么?

+0

模拟器不能像手机一样工作。他们没有GPS或网络,虽然你可以用一些工具和设置来模拟地理坐标。[点击此链接](http://stackoverflow.com/questions/2279647/how-to-emulate-gps-location-in -the-android-emulator) –

回答

2

最好的方法是使用Google Play Services库提供的最新FusedLocationApi。

如果你想使用旧的方法,那很好,但你可能得不到非常准确的结果。

无论哪种方式,请确保您已启用互联网权限,无论是COARSE_LOCATION或FINE_LOCATION或在您的Android清单。此外,如果您有Android 6.0,请记住您必须请求运行时权限,否则它不适用于您!

我昨天回答了一个类似的问题,你可以找到here - 哪些工作;

还有一个链接到FusedLocationApi here的示例代码。

我希望这可以帮助你,祝你好运!

UPDATE

您可以添加谷歌Play服务您的build.gradle这样的:

compile 'com.google.android.gms:play-services:9.2.' 

但是如果你只对像位置的一个服务有兴趣,你可以具体:

compile 'com.google.android.gms:play-services-location:9.2.1' 

注意

我会极力阻止你在用户界面线程上获取用户位置,因为它会长期破坏用户体验!使用一个单独的线程!

+0

感谢您的回答,我只是有一个简单的问题。当你说谷歌播放服务时,它是否在谷歌开发者控制台中被称为“谷歌播放游戏服务”?(对不起,新手在这) –

+0

'FuesdLocationApi'也使用'gps'来获得'coarse_location'的精确位置和网络,所以使用gps时,其位置几乎与'FusedLocation'相同'high_accuracy'标志在内部使用gps –

+0

我已更新回答 – Eenvincible

0

你必须模仿模拟器中的位置。您可以通过访问Android设备管理器和选择模拟器控制选项卡并将位置发送到模拟器来完成此操作。

Location settings in Emulator