写一个能定位位置的Android代码
时间: 2023-02-11 20:57:15 浏览: 93
下面是简单的定位代码示例,使用Google Play服务的FusedLocationProviderClient类进行定位:
```java
public class MainActivity extends AppCompatActivity {
private FusedLocationProviderClient fusedLocationClient;
private TextView locationText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationText = findViewById(R.id.location_text);
// Get the location client
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
// Request location updates
fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
locationText.setText("Latitude: " + location.getLatitude() + "\nLongitude: " + location.getLongitude());
}
}
});
}
}
```
请注意,在使用定位功能之前,您需要在应用程序的AndroidManifest.xml文件中添加定位权限:
```xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
```
此代码示例将会在成功获取地理位置后显示经纬度,如果需要地址信息,可使用Geocoder类转换。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)