android studio获取定位的代码
时间: 2023-10-18 15:13:20 浏览: 94
以下是使用Android Studio获取用户定位的代码:
1. 在AndroidManifest.xml文件中添加以下权限:
```xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
```
2. 在你的Activity中添加以下代码:
```java
public class MainActivity extends AppCompatActivity implements LocationListener {
private LocationManager locationManager;
private String provider;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 获取系统定位服务
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// 获取最佳定位方式
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
// 获取用户当前位置
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
return;
}
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
} else {
Toast.makeText(this, "定位失败", Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onResume() {
super.onResume();
// 监听用户位置变化
locationManager.requestLocationUpdates(provider, 1000, 1, this);
}
@Override
protected void onPause() {
super.onPause();
// 停止监听用户位置变化
locationManager.removeUpdates(this);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// 获取用户当前位置
if (requestCode == 100) {
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
onLocationChanged(location);
} else {
Toast.makeText(this, "定位失败", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onLocationChanged(Location location) {
// 获取用户当前位置的经纬度
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Toast.makeText(this, "您的当前位置:" + latitude + ", " + longitude, Toast.LENGTH_SHORT).show();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
}
```
这些代码将获取用户最佳定位方式,并在用户位置变化时显示用户当前位置的经纬度。记得添加相关权限并处理用户拒绝授权的情况。
阅读全文